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

如何使用Axios.post同时发送JSON请求体与MP4多部分表单数据并解决415报错

问题解决方案

错误原因梳理

  • 前端侧错误:
    1. FormData字段名重复,两次调用append都使用了file作为键名,导致details参数覆盖了部分文件数据
    2. 直接将JS对象传入FormData,没有序列化为JSON字符串,传输时会被转为[object Object]无效内容
    3. 手动设置了multipart/form-data请求头,缺失了浏览器自动生成的boundary分界符,导致后端无法解析多部分请求内容
  • 后端侧错误:
    1. 在multipart/form-data类型的请求中使用@RequestBody接收参数,@RequestBody仅适用于请求体为纯JSON的场景,无法解析多部分表单中的字段

前端代码修改

const handleSubmission=(e)=>{
    e.preventDefault();
    const data = new FormData();
    // 追加文件字段,键名保持file
    data.append("file", file)
    // 追加details字段,先转JSON字符串,键名用details
    data.append("details", JSON.stringify(details))

    // 删掉手动设置的Content-Type头,浏览器会自动生成带boundary的正确头
    axios.post(`${process.env.REACT_APP_URL_NEW_ROUND_VID}/123/file/upload`, data)
    .then(res=>{
        console.log("Data: ",res.data)
        console.log("success")
    })
    .catch((e)=>{
        console.log("Error", e)
    })
};

后端代码修改

推荐使用@RequestPart注解,Spring会自动将JSON格式的表单字段转为对应实体类:

@PostMapping(
   path = "{patientId}/file/upload",
   consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
   produces = MediaType.APPLICATION_JSON_VALUE)
public void addWardRound(@PathVariable("patientId") String patientId,
                          @RequestPart("file") MultipartFile file,
                          // 用@RequestPart接收details字段,自动反序列化为WardRequest
                          @RequestPart("details") WardRequest wardRequest){
    WardRoundService.isFileEmpty(file);
    WardRound round = service.saveRound(wardRequest);
    String roundId = round.getRoundId();
    service.uploadVid(patientId, roundId, file);
}

如果遇到兼容性问题,也可以手动接收JSON字符串后反序列化:

@PostMapping(
   path = "{patientId}/file/upload",
   consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
   produces = MediaType.APPLICATION_JSON_VALUE)
public void addWardRound(@PathVariable("patientId") String patientId,
                          @RequestParam("file") MultipartFile file,
                          @RequestParam("details") String detailsJson,
                          ObjectMapper objectMapper) throws JsonProcessingException {
    WardRequest wardRequest = objectMapper.readValue(detailsJson, WardRequest.class);
    // 原有业务逻辑不变
    WardRoundService.isFileEmpty(file);
    WardRound round = service.saveRound(wardRequest);
    String roundId = round.getRoundId();
    service.uploadVid(patientId, roundId, file);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:06:02