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

React使用Axios同时提交数据和图片,服务端无法读文件且不能用multer如何解决

问题解决方法

核心问题原因

你目前的写法不符合multipart/form-data的协议要求:将FormData文件对象和普通业务对象嵌套在同一个JSON payload中提交,会导致文件数据被异常序列化丢失,所以服务端只能拿到普通字段,拿不到文件。

客户端修改

所有要提交的内容(包括业务字段、文件)必须全部放到同一个FormData实例中提交,复杂的业务对象可以转成JSON字符串后再加入FormData:

public add = async () => {
  const newVacation = new Vacation(
    // values of the vacations that are coming from inputs 
  )

  try {
    // 所有内容都放在同一个FormData里
    const formData = new FormData();
    // 添加文件相关字段
    formData.append("imageName", newVacation.imageName);
    formData.append("image", newVacation.image[0]);
    // 业务对象转成JSON字符串后加入表单
    formData.append("reqNewVacation", JSON.stringify(newVacation));
  
    const response = await jwtAxios.post('http://localhost:4000/admin/addvacations', formData, {
      headers: {
        // 这里可以不用手动写Content-Type,axios会自动根据FormData设置带正确boundary的请求头,手动写反而可能漏boundary导致解析失败
        'Content-Type': 'multipart/form-data' 
      }
    })

  } catch (error) {
    console.log(error);
  } 
}

服务端修改

从body中拿到业务字段的JSON字符串后反序列化为对象,直接读取文件即可:

router.post("/addvacations", async (request, response) => {
  try {
    // 反序列化得到业务对象
    const newVacation = JSON.parse(request.body.reqNewVacation)
    const addedvacation = await vacationLogic.addVacationAsync(newVacation);
    
    // 直接读取文件和图片名
    const imageName = request.body.imageName
    const image = request.files.image
    const absolutePath = path.join(__dirname, "..", "upload", image.name);
    await image.mv(absolutePath);

    response.status(200).send("新增成功")
  } catch (error) {
    response.status(500).send(error.message)
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:00:01