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

使用Flutter对接Node.js API上传图片时req.file返回undefined如何解决

问题排查及修复方案

1. 前端Flutter代码问题:手动设置错误的multipart请求头

http.MultipartRequest 会自动生成包含boundary分隔符的Content-Type请求头,你手动添加的{"Content-type": "multipart/form-data"}缺少必填的boundary参数,导致multer无法正确解析表单数据,直接忽略上传的文件。
修复方法:删除手动添加headers的代码即可。
修改后的uploadImage方法代码:

uploadImage() async {
  final request = http.MultipartRequest(
      "POST", Uri.parse("http://192.168.1.65:9000/api/v1.0.0/events/create"));
  request.files.add(http.MultipartFile('img',
      selectedImage!.readAsBytes().asStream(), selectedImage!.lengthSync(),
      filename: selectedImage!.path.split("/").last));
  final response = await request.send();
  http.Response res = await http.Response.fromStream(response);
  final resJson = jsonDecode(res.body);
  message = resJson['message'];
  setState(() {});
}

2. 后端Node.js代码问题:png格式mimetype判断错误

你的fileFilter逻辑里,png格式的mimetype写错为images/png,正确值是image/png,所有png格式的图片都会被过滤掉,导致req.file为undefined。
修复方法:修正fileFilter里的判断条件:

const fileFilter = (req, file, cb) => {
    if (file.mimetype == "image/jpeg" || file.mimetype == "image/png") {
        cb(null, true)
    } else {
        cb(null, false)
    }
}

3. 可选优化点:响应状态码传值类型修正

路由返回时status('200')传了字符串类型,Express虽然会自动转换,但建议传入标准数字类型:

return res.status(200).send(response)

修复以上两个核心问题后,即可正常接收到上传的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 05:45:01