Thursday, June 18 2020
In this tutorial, we discuss about How to Integrate File Upload using Multer with Node.js and Express JS. File upload is a very common operation in any application. In node.js adding a file upload feature using multer package to add a file very easy to app. Here we are going to see file upload operation in two ways.
First, we see the file upload with Multer in Node.js and Express JS using Postman.
npm install express --save npm install path --save npm install multer --save
Your project setup look like this
In app.js file create a server with following contents
// load express const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('hello world'); }); app.listen(3000, () => { console.log('Started on port 3000'); });
Now run the file using the below command in the terminal.
node app.js
After this, You can get the server URL http://localhost:4000/ Open the browser and check that URL.
Adding multer package in app.js using require() method.
const multer = require('multer'); const upload = multer({dest:'uploads/'}).single("file_image");
In the above code dest option used to store the file in the specified directory. If you omit this file doesn’t written in the disk.
The disk storage engine gives you full control over storing files to disk. We will create a storage object using the diskStorage() method.
The following code will go in app.js
var storage = multer.diskStorage({ destination: function (req, file, cb) { // Uploads is the Upload_folder_name cb(null, "uploads") }, filename: function (req, file, cb) { cb(null, file.fieldname + "-" + Date.now()+ path.extname(file.originalname)) } });
Here, there are two properties, destination, and filename. They both are functions.
destination: used to allows you to which directory you want to store the uploaded files.
filename: used to determine what the file should be named inside the folder.
null: Don’t want to show any error.
const maxSize = 1 * 1000 * 1000; // max 1 MB var upload = multer({ storage: storage, limits: { fileSize: maxSize }, fileFilter: function (req, file, cb){ // Set the filetypes, it is optional var filetypes = /jpeg|jpg|png/; var mimetype = filetypes.test(file.mimetype); var extname = filetypes.test(path.extname(file.originalname).toLowerCase()); if (mimetype && extname) { return cb(null, true); } cb("Error: File upload only supports the " + "following filetypes - " + filetypes); } // file_image is the name of file attribute }).single("file_image");
The following code will go in app.js:
app.post("/imageUpload", (req, res) => { upload(req, res, (err) => { if(err) { res.status(400).send("Something went wrong!"); } res.send(req.file); }); });
Run the app.js file and check this URL http://localhost:4000/imageUpload in Postman.
You need to install ejs package that helps to integrate form in node.js.
npm install ejs --save
Update the following code in app.js
app.engine('html', require('ejs').renderFile); app.set('view engine', 'ejs'); app.set('views',path.join(__dirname,'views'));
Created views directory for html related files such as forms, layouts are inside this folder.
mkdir views cd views touch fileupload.ejs
In fileupload.ejs file inside .views/ directory with following contents
<!DOCTYPE html> <html> <head> <title>FILE UPLOAD DEMO</title> </head> <body> <h1>File Upload Demo</h1> <form action="/imageUpload" enctype="multipart/form-data" method="POST"> <span>Upload Profile Picture:</span> <input type="file" name="file_image" required/> <br> <input type="submit" value="submit"> </form> </body> </html>
In app.js file update the following contents
app.get('/', function(req, res) { res.render('fileupload'); });
To run app.js file in the terminal http://localhost:4000/
Finally app.js file integrated with all codes
// load express const express = require('express'); const multer = require('multer'); const path = require('path'); const app = express(); // ejs for html template app.engine('html', require('ejs').renderFile); app.set('view engine', 'ejs'); app.set('views',path.join(__dirname,'views')); // Disk storage var storage = multer.diskStorage({ destination: function (req, file, cb) { // Uploads is the Upload_folder_name cb(null, "uploads") }, filename: function (req, file, cb) { cb(null, file.fieldname + "-" + Date.now()+ path.extname(file.originalname)) } }); // multer upload options const maxSize = 1 * 1000 * 1000; // max 1 MB var upload = multer({ storage: storage, limits: { fileSize: maxSize }, fileFilter: function (req, file, cb){ // Set the filetypes, it is optional var filetypes = /jpeg|jpg|png/; var mimetype = filetypes.test(file.mimetype); var extname = filetypes.test(path.extname(file.originalname).toLowerCase()); if (mimetype && extname) { return cb(null, true); } cb("Error: File upload only supports the " + "following filetypes - " + filetypes); } // file_image is the name of file attribute }).single("file_image"); // routing for home page app.get('/', function(req, res) { res.render('fileupload'); }); // routing for file upload app.post("/imageUpload", (req, res) => { upload(req, res, (err) => { if(err) { res.status(400).send("Something went wrong!"); } res.send(req.file); }); }); // create server app.listen(4000, () => { console.log('Started on port 4000'); });
Building a Restful CRUD API with Node.js Express and MongoDB