当字段为空时停止multer上载

ddrv8njm  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(367)

我正试图向用户发出一个post请求,要求他们一次更新其个人资料的多个部分,但是如果他们只想更新他们的个人资料,而不想更新他们的个人资料图片,例如,如果字段留空,我如何阻止multer尝试上传?
后请求:

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

多存储选项:

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

当我将其留空时,得到的错误是

TypeError: Cannot read property 'filename' of undefined
2nbm6dog

2nbm6dog1#

只需检查是否添加了任何文件 if (!req.file) { //Dont do anything since there is no file } else { //do something const fileName = req.file.filename; }

相关问题