Stop multer from uploading when field is empty

Viewed 463

I'm trying to make a post request for users to update multiple parts of their profile at once, but if they only want to update their bio and not their profile picture for example, how can I stop multer from trying to upload if the field is left blank?

post request:

app.post('/updateprofile/:user_id',  upload.single("profilePic"), function(req, res){
  let newPic = req.file.filename
  let bio = req.body.bio
  ...
})

multer storage options:

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

When I leave it empty the error I get is

TypeError: Cannot read property 'filename' of undefined
1 Answers

just check if any file was added with if (!req.file) { //Dont do anything since there is no file } else { //do something const fileName = req.file.filename; }

Related