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

使用Postman通过form-data上传商品时提示‘Image file is missing or invalid’错误

问题排查:Postman form-data上传商品时提示“Image file is missing or invalid”

在使用Postman通过form-data上传商品时,触发了“Image file is missing or invalid”错误,本地已存储图片数据,表单数据及错误信息见截图。

控制器代码

exports.create = (req, res) => {
  let form = new formidable.IncomingForm();
  form.keepExtensions = true;
  form.parse(req, async (err, fields, files) => {
    if (err) {
      return res.status(400).json({
        error: "Image could not be uploaded",
      });
    }
    let product = new Product(fields);

    // use same name as model and file name type

    if (files.photo && files.photo.path && files.photo.type) {
      const filePath = path.normalize(files.photo.path);
      const fileType = mime.getType(files.photo.type);
      product.photo.data = fs.readFileSync(filePath);
      product.photo.contentType = fileType;
    } else {
      // handle error
      return res.status(400).json({
        error: "Image file is missing or invalid",
      });
    }
    // continue with other code
    try {
      const result = await product.save();
      res.json(result);
    } catch (err) {
      return res.status(400).json({
        error: errorHandler(err),
      });
    }
  });
};

排查与解决步骤

  • 严格匹配字段名:代码中判断的是files.photo,Postman里form-data的文件字段Key必须完全等于photo(大小写一致),否则会直接触发错误分支。
  • 完善formidable配置:添加文件大小限制,避免大文件被拦截:
    form.maxFileSize = 5 * 1024 * 1024; // 设置为5MB,可根据业务需求调整
    
  • 调试文件接收状态:在form.parse回调内打印files对象,确认是否正确接收到文件:
    console.log('Received files:', files);
    
    若files.photo不存在,检查Postman是否正确选择了本地文件;若存在但path或type为空,尝试将formidable更新到最新版本。
  • 修复MIME类型逻辑:files.photo.type本身就是标准MIME类型,无需通过mime.getType二次转换,直接赋值即可:
    product.photo.contentType = files.photo.type;
    
    若files.photo.type为空,可通过文件扩展名获取MIME类型:
    const ext = path.extname(files.photo.name);
    product.photo.contentType = mime.getType(ext);
    
  • 修正路径解析:使用path.resolve替代path.normalize,避免系统路径解析异常:
    const filePath = path.resolve(files.photo.path);
    
  • 检查文件权限:确保Node.js进程拥有读取系统临时目录文件的权限(formidable默认将上传文件存储在系统临时目录)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:23:12