Multer in Nodejs using Express Router req.file undefined

161 Views Asked by At

I am trying to implement File Upload functionality using multer and Express Router. I defined an endpoint /batch_upload using router.use like below

api.js

router.use(
  "/batch_upload",
  upload.single("emp_csv_data"),
  userController.processBatchUserInformation
);

in userController.js

exports.processBatchUserInformation = async (req, res) => {
  console.log(req.file);

  if (req.method == "POST") {
    try {
      console.log("Upload route reached - POST");
      console.log(req.file);
      console.log(req.file.path);
      return res.send(req.file);
    } catch (err) {
      console.log("Error Occurred");
      return res.send(err);
    }

  }
};

In the FileUploader.js, I defined the upload variable and multer options like below

var multer = require("multer");

var storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads");
  },
  filename: (req, file, cb) => {
    return cb(null, file.fieldname + "-" + Date.now());
  }
});


exports.upload = multer({ storage: storage });

Finally, in the app.js I used the route using app.use('/user',user_routes)

But when I send a file to http://localhost:5000/user/batch_upload, I get an undefined response for req.file

enter image description here

Irony is that I have the exact implementation in a sample test project and everything seems fine. I don't understand what am I missing. If you see something that seems off, please help me fix it.

1

There are 1 best solutions below

1
On

So, the reason behind the file not being uploaded was that I did not add Content-type:multipart/form-data in the headers. Thank you guys for trying to help. I appreciate it.