How to upload file in node js using multer

Posted By : Ankit Singh Rana | 03-Sep-2017

Multer is a middleware in node js, which is used for uploading files. To get started we would need to install it via npm

           npm install --save multer
        

Now first we require it and define its destination and some filter. Below is an example.

            var multer  = require('multer'); // Require it
            var upload = multer({ dest: 'public/img' },{ // Set the destination
					  fileFilter: function (req, file, cb) { // a custom filter
						    if (mimeType.indexOf(file.mimetype) != -1) {
						    	return cb(null, false);
						    }
						    cb(null, true);
						  }
		                });
        

In fileFilter function, we can define which type of file, the API would accept etc. In dest, we would define where the file will be saved on the server.

Now, all we need is to use this middleware where we want to upload the file.

           router.post('/',upload.array('images'), function(req, res) {});
        

Upload.array will take images array. The name of the array is images, you can name it anything you want. 

To upload a single file we will use ".single" function shown below.

            router.post('/',upload.single('image'), function(req, res) {});
        

This will upload a single file name image. Also, req.body will also hold the text field as well.

You can also pass an array of objects if you want, where filename would be the key and value would be the array of files.

Below is an example

            var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
           router.post('/',upload.array('cpUpload'), function(req, res) {});
        

As you can see, you can also define a number of files you want to upload.

Also note that this middleware uses busboy parser by default. And make sure to add multipart/form-data in the form.

About Author

Author Image
Ankit Singh Rana

Ankit is a UI Developer having experience in Angular 2, Angular JS, JavaScript, HTML5 and CSS3. His hobbies includes playing video Games and traveling.

Request for Proposal

Name is required

Comment is required

Sending message..