在 Spring Boot 应用里,前端经常需要在一次提交中既上传文件又携带 JSON 格式的业务数据,例如用户资料图片加用户基本信息。借助 HTTP 的 multipart 请求,我们可以在单个请求中同时传输二进制文件和文本类型的 JSON,后端通过合适注解即可分别解析。

后端接口如何编写
我们可以使用 @RequestPart 注解来分别接收文件和 JSON 部分。当 JSON 作为文本部分传递时,可先接收为字符串,再用 ObjectMapper 转换;也可以直接让 Spring 帮我们反序列化。
定义数据对象
// 用户数据传输对象
public class UserDTO {
private String name;
private Integer age;
// 省略 getter 和 setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
控制器示例
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
@RestController
public class UploadController {
private final ObjectMapper objectMapper = new ObjectMapper();
@PostMapping("/upload")
public String handleUpload(
@RequestPart("file") MultipartFile file,
@RequestParam("data") String jsonData) throws Exception {
// 将 JSON 字符串解析为对象
UserDTO user = objectMapper.readValue(jsonData, UserDTO.class);
// 这里可以处理文件和用户数据
return "文件名:" + file.getOriginalFilename() + ",用户:" + user.getName();
}
}
前端如何发送请求
前端使用 FormData 来构造请求体,把文件和 JSON 字符串都追加进去,并以 multipart/form-data 方式发送。
<form id="f">
<input type="file" id="file" />
<input type="text" id="name" />
<input type="number" id="age" />
<button type="button" onclick="submitForm()">提交</button>
</form>
<script>
function submitForm() {
var fd = new FormData();
fd.append("file", document.getElementById("file").files[0]);
var user = {
name: document.getElementById("name").value,
age: document.getElementById("age").value
};
fd.append("data", JSON.stringify(user));
fetch("/upload", {
method: "POST",
body: fd
}).then(function(r){ return r.text(); })
.then(function(t){ console.log(t); });
}
</script>
常见注意点
- Spring Boot 默认开启 multipart 支持,但需注意文件大小限制,可在配置中调整。
- 如果 JSON 部分使用
@RequestPart直接接收对象,前端 FormData 中该部分应设为普通文本,且 Content-Type 为 application/json。 - 避免用 <input> 标签误解为函数调用,input() 才是脚本函数,书写时注意区分。
合理运用 multipart 请求,可让文件与 JSON 在同一个 HTTP 请求中稳定传输,简化前后端交互逻辑。
小结
通过 MultipartFile 与 @RequestPart 或 @RequestParam 的配合,Spring Boot 能够轻松实现单请求上传文件与 JSON 数据。只要前端正确构造 FormData,后端按部分解析即可满足大多数业务场景。
Spring_Boot文件上传JSON修改时间:2026-07-27 10:51:20