【问题标题】:unable to post empty image file in nodejs using multer无法使用 multer 在 nodejs 中发布空图像文件
【发布时间】:2020-10-20 10:29:26
【问题描述】:

我想发布带有或不带有图像文件的表单。我可以上传图像文件,但在尝试上传没有图像文件时它会向我发送错误 我的代码是

  router.post('/fabric', upload.any([{
  name: 'image', maxCount:1}, {
    name: 'design'
  }]), (req, res, next) => {
  const io = req.app.get('io');

  const product = new db.fabric({
    image: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files[0].filename,
    mobilenumber: req.body.mobilenumber,
    email: req.body.email,
    design: req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files[1].filename
  });

  product.save().then(result => {
    res.status(201).json({
      message: "product added successfully!",
      productCreated: {
        image: result.image,
        design: result.design,
        mobilenumber: result.mobilenumber,
        email: result.email
      }
    })
    io.emit('productAdded');
  }).catch(err => {
    console.log(err),
      res.status(500).json({
        error: err
      });
  })
})

当我从没有图像字段的邮递员发帖时,出现以下错误

TypeError: Cannot read property 'filename' of undefined

【问题讨论】:

    标签: node.js multer image-upload


    【解决方案1】:

    您需要申请支票

        const product = new db.fabric({
        image: req.files.length>0 && req.files[0]?req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files[0].filename:"",
        mobilenumber: req.body.mobilenumber,
        email: req.body.email,
        design: req.files.length>0 && req.files[1]?req.protocol + "://" + req.hostname + ":" + req.socket.localPort + "/img/" + req.files[1].filename:""
      });
    

    还要确保在 db image 和 design 中不是必填字段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 2023-04-05
      • 2019-12-05
      • 1970-01-01
      • 2021-05-03
      • 2021-11-23
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多