loading...
Cover image for Uploading multiple files with multer, but from different fields Node JS

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

zeeshanmehdi profile image zeeshan mehdi Updated on ・1 min read

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('/')
  });

})

Posted on by:

zeeshanmehdi profile

zeeshan mehdi

@zeeshanmehdi

I am professional Mobile Developer usually do my work on flutter. I am machine learning Enthusiast learning new things each day.

Discussion

pic
Editor guide