Thursday 13 June 2019

Receiving a request with multiple file fields in NodeJS using multer

Multer is a handy module that enables the node API to upload files at ease. We can upload an array of files or files in separate fields or a single file using multer.

Let's see how one can upload files in received in separate fields.

In the following example, we are going to develop a request to upload a resume and a profile photo with field names 'resume' and 'profile_pic' respectively.

Receiving Request

var express = require('express');
var multer = require('multer');
var upload = multer({
    dest: 'upload_folder'
});
var app = express();

var upload_files = upload.fields([{
    name: 'resume',
    maxCount: 1
}, {
    name: 'profile_pic',
    maxCount: 8
}]);

app.post('/upload-profile', upload_files, 
     function(req, res, next) {
    console.dir(req.files); //prints the array of uploaded files

});

app.listen(parseInt(3200));


The following code is to be placed in your localhost(html folder):

Sending Request

<form action="http://localhost:3200/upload-profile" method="post" 
      enctype="multipart/form-data">
    <div>

        <label>Upload Resume</label> <input type="file" 
          name="resume" />

        <label>Upload profile pic</label> <input type="file" 
                    name="profile_pic" />

        <input type="submit" value="Submit">

    </div>

</form>


Hope this helps! Happy coding!