DEV Community

Cover image for Uploading multiple files with multer, but from different fields Node JS
zeeshan mehdi
zeeshan mehdi

Posted on • Updated on

Uploading multiple files with multer, but from different fields Node JS

i was in a situation where i were to upload audio file along with a graphic for that particular song so i was to upload to different files an image and audio file so i used a way to do that using multer plugin available on link

var multer = require('multer')
var storage = multer.diskStorage({


destination: function(req, file, callback) {
    callback(null, './public/audio');
  },
  filename: function(req, file, callback) {
    console.log(file);
    if(file.originalname.length>6)
      callback(null, file.fieldname + '-' + Date.now() + file.originalname.substr(file.originalname.length-6,file.originalname.length));
    else
      callback(null, file.fieldname + '-' + Date.now() + file.originalname);

  }
});

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


router.post('/save/audio',upload.fields([{
  name: 'audio', maxCount: 1
}, {
  name: 'graphic', maxCount: 1
}]) ,(req, res) => {

  const audioFile = req.files.audio[0];
  const audioGraphic = req.files.graphic[0];
  const fileName = req.body.title;


  saveAudio(fileName,audioFile.filename,audioGraphic.filename,req.body.artist,function (error,success) {
    req.flash('success','File Uploaded Successfully')

    res.redirect('/')
  });

})
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
rshrmcse profile image
badcaptain0001

this one is really useful and less code

Collapse
 
farzanfx profile image
Farzan

Thanks for snippet it saved me a lot of time!

Collapse
 
zeeshanmehdi profile image
zeeshan mehdi

glad to hear