Search code examples
javascriptnode.jsexpressmulter

Uploading multiple files with multer in express


I was trying to allow uploading of multiple files to my express app but I fell into an error. What's wrong with this code?

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./uploaded");
  },

  filename: function (req, file, cb) {
    cb(null, file.originalname);
  },
});

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

router.post("/upload_img", upload.single("fileupload"), (req, res, err) => {
  if (err) {
    console.log(err);
  } else {
    res.redirect("/upload?upload success");
    console.log(req.files);
  }
});


Solution

  • You specified:

    upload.single('fileupload')
    

    Change that to:

    upload.array('fileupload')
    

    Or you can also do this:

    upload.any()
    

    If you go with upload.any(), you can upload one file or multiple files, and you don't need to specify field name.