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

使用Multer添加图片数组时Postman返回名称undefined问题求助

Multer上传图片返回路径含undefined的解决办法

问题原因

你代码里用file.fileName获取文件名,但Multer生成的文件对象中,文件名对应的属性是**filename**(全小写),驼峰式的fileName不存在,所以拼接路径时会出现undefined。

修复后的代码

router.put(
  "/gallery-images/:id",
  uploadOptions.array("images", 10),
  async (req, res) => {
    if (!mongoose.isValidObjectId(req.params.id)) {
      return res.status(400).send("Invalid product ID"); // 补充return,避免后续代码执行
    } 
    const files = req.files;
    let imagesPaths = [];
    const basePath = `${req.protocol}://${req.get("host")}/public/upload/`;
    if (files) {
      files.map((file) => {
        imagesPaths.push(`${basePath}${file.filename}`); // 替换fileName为filename
        console.log("uhu", file);
      });
    }
    let product = await Product.findByIdAndUpdate(
      req.params.id,
      {
        images: imagesPaths,
      },
      { new: true }
    );
    if (!product) return res.status(500).send("The product cannot be updated");
    res.send(product);
  }
);

额外提示

  • 原代码中ID校验逻辑没有终止响应,即使ID无效,后续代码仍会执行,建议加上return提前结束请求。
  • 可以通过console.log(file)打印文件对象的完整结构,确认属性名称,避免类似拼写错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:30:55