Uploading multiple files with multer, but from different fields?

Andre M picture Andre M · Mar 19, 2016 · Viewed 32.2k times · Source

How can I have multer accept files from multiple file type fields?

I have the following code that uploads a single file, using multer in node.js:

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './public/uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage : storage });

app.post('/rest/upload', upload.array('video', 1), function(req, res, next){
    ...
}

From the following form, on the condition only the video field has a value (if I specify both I get an 'Unexpected field' error):

<form action="/rest/upload" method="post" enctype="multipart/form-data">
   <label>Video file: </label> <input type="file" name="video"/> 
   <label>Subtitles file: </label> <input type="file" name="subtitles"/> 
   <input type="submit"/>
</form>

It is not clear from the documentation how to approach this? Any suggestions would be appreciated. BTW I have tried the following parameter variations, without success:

app.post('/rest/upload', [upload.array('video', 1), upload.array('subtitles', 1)] ...
app.post('/rest/upload', upload.array('video', 1), upload.array('subtitles', 1), ...
app.post('/rest/upload', upload.array(['video', 'subtitles'], 1),  ...

Answer

mscdex picture mscdex · Mar 19, 2016

What you want is upload.fields():

app.post('/rest/upload',
         upload.fields([{
           name: 'video', maxCount: 1
         }, {
           name: 'subtitles', maxCount: 1
         }]), function(req, res, next){
  // ...
}