Spring Boot POST接口同时接收MultipartFile与JSON对象报错求助
Spring Boot POST端点同时接收文件与JSON元数据的415错误解决
问题场景
需要实现一个POST端点,同时接收:
- 从Windows资源管理器上传的
MultipartFile(如xlsx、doc等格式文件) - 作为字符串提供的JSON元数据,示例JSON:
{ "address": "string", "fullName": "string" }
原有实现代码:
控制器代码
@PostMapping(path = "/post", consumes = {"application/json","multipart/form-data"}) public ResponseEntity<String> endpoint( @RequestBody ReportDto reportDto, @RequestPart("myFile") MultipartFile myFile ){ return ResponseEntity.ok(service.process(reportDto,myFile)); }
ReportDto类
public class ReportDto{ String address; String fullName; // getters // setters // 全参构造方法 // 无参构造方法 }
调用时通过Swagger、POSTMAN或以下curl请求均返回HTTP 415: Unsupported Media错误:
curl -X 'POST' \ 'http://localhost:8080/api/v1/dashboards/post' \ -H 'accept: */*' \ -H 'Authorization: Bearer somebearertoken' \ -H 'Content-Type: multipart/form-data' \ -F 'reportDto={ "address": "string", "fullName": "string" }' \ -F 'myFile=@Table_New.xlsx;type=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
错误原因
- 注解混用错误:
@RequestBody用于解析整个请求体为JSON/XML,但当前请求是multipart/form-data类型,JSON只是其中一个part,不能用@RequestBody,需改用@RequestPart。 - Consumes配置冗余:请求实际是
multipart/form-data类型,无需同时声明application/json。 - curl请求缺少Content-Type声明:JSON part未指定
type=application/json,Spring无法识别该part为JSON格式,无法自动转换为ReportDto对象。
修正方案
1. 修改控制器代码
将@RequestBody替换为@RequestPart,并调整consumes为仅multipart/form-data:
@PostMapping(path = "/post", consumes = "multipart/form-data") public ResponseEntity<String> endpoint( @RequestPart("reportDto") ReportDto reportDto, @RequestPart("myFile") MultipartFile myFile ){ return ResponseEntity.ok(service.process(reportDto,myFile)); }
2. 修正curl请求
为reportDto部分添加type=application/json声明:
curl -X 'POST' \ 'http://localhost:8080/api/v1/dashboards/post' \ -H 'accept: */*' \ -H 'Authorization: Bearer somebearertoken' \ -H 'Content-Type: multipart/form-data' \ -F 'reportDto={ "address": "string", "fullName": "string" };type=application/json' \ -F 'myFile=@Table_New.xlsx;type=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
3. POSTMAN/Swagger调用注意事项
- 在POSTMAN中,选择
form-data格式,reportDto字段的Type设为text,并在值中输入JSON内容,同时在该字段的Headers里添加Content-Type: application/json。 - Swagger中需确保
reportDto参数的媒体类型设置为application/json。
内容的提问来源于stack exchange,提问作者ripunjoym1998
相关产品推荐
相关产品推荐

