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

如何用Axios实现Spring Boot多表单数据(文件+对象)上传请求

解决Axios调用Spring Boot @RequestPart接口的配置问题

问题根源

直接用JSON格式传UserDTO会导致Content-Type不匹配,Spring Boot的@RequestPart要求每个请求部分都符合对应类型,而且请求必须是multipart/form-data格式,且边界值得由浏览器自动生成,手动指定反而会出错。

正确的Axios实现代码

前端Axios请求示例

必须用FormData来封装参数,把UserDTO转成指定类型的Blob,再和文件一起加入FormData:

// 构造你的UserDTO数据
const userData = {
  username: "zhangsan",
  age: 30
};

// 把JSON对象转成Blob,指定Content-Type为application/json
const userBlob = new Blob([JSON.stringify(userData)], {
  type: "application/json"
});

// 构建FormData,注意key要和后端@RequestPart的参数名完全一致
const formData = new FormData();
formData.append("userDTO", userBlob); // 对应后端@RequestPart("userDTO")
formData.append("file", document.getElementById("fileInput").files[0]); // 对应后端@RequestPart("file")

// 发起Axios请求
axios.post("/add", formData)
  .then(res => {
    console.log("请求成功", res.data);
  })
  .catch(err => {
    console.error("请求失败", err);
  });

注意:不需要手动设置Content-Type: multipart/form-data,浏览器会自动添加这个头以及正确的边界值,手动设置反而会引发"缺少multipart边界"的错误。

后端接口参数确认

确保后端接口的@RequestPart参数名和前端FormData的key完全对应:

@PostMapping("/add")
public ResponseEntity<String> addUser(
    @RequestPart("userDTO") UserDTO userDTO,
    @RequestPart("file") MultipartFile file
) {
    // 处理业务逻辑
    return ResponseEntity.ok("操作成功");
}

常见错误避坑

  • 不要直接把UserDTO对象塞进FormData,必须转成Blob并指定application/json类型,否则会触发InvalidContentTypeException
  • 禁止手动设置multipart/form-data的边界值,浏览器会自动生成正确的边界
  • 前后端参数名必须严格一致,包括大小写,否则后端无法正确绑定参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:10:20