You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Multer中设置未上传图片时的默认值,避免服务报错并正常存储数据

问题原因
  • 当未上传图片时,multer的upload.single("image")中间件不会在请求对象上挂载req.file属性,此时直接访问req.file.originalname会触发undefined属性访问报错,打断业务流程。
  • 你的数据模型已经为image字段设置了默认值,无需手动赋值即可在字段为空时自动填充默认图片。
修复方案

只需修改/add接口的逻辑,新增对req.file是否存在的判断即可:

router.route('/add').post(upload.single("image"), (req, res) => {
    // 先构造基础数据对象
    const clientData = {
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      weight: req.body.weight,
      BMI: req.body.BMI
    }
    // 只有存在上传文件时才添加image字段
    if (req.file) {
      clientData.image = req.file.originalname
    }

    const newClient = new Clients(clientData)

    newClient.save()
    .then (() => res.json(newClient))
    .catch(err => res.status(400).json('error' + err))
})

内容的提问来源于stack exchange,提问作者Chen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 23:15:03