org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'multipart/form-data;boundary=----WebKitFormBoundaryRAYPKeHKTYSNdzc1;charset=UTF-8' not supported
使用 FormData
Ajax 上传文件,后台使用 Spring boot,报 org.springframework.web.HttpMediaTypeNotSupportedException
错误:
org.springframework.web.HttpMediaTypeNotSupportedException:
Content type 'multipart/form-data;boundary=----WebKitFormBoundaryRAYPKeHKTYSNdzc1;charset=UTF-8' not supported
ajax 文件上传:
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: url,
type: 'post',
data: formData,
contentType: false,
processData: false,
success: function(data) {
self.onSuccess(data);
self.deleteFile(file);
},
error: function(data) {
self.onFailure(data);
}
});
后台 Controller 接口:
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file, @RequestBody User user) {
// 业务处理
}
除了后台报错的日志,使用 Postman 测试返回的消息头:
"timestamp": 1536114316870,
"status": 415,
"error": "Unsupported Media Type",
"exception": "org.springframework.web.HttpMediaTypeNotSupportedException",
"message": "Content type 'multipart/form-data;boundary=----WebKitFormBoundaryTVc9eDC2a2elulOx;charset=UTF-8' not supported",
"path": "/upload"
已采纳
FormData
上传文件的时候,Content Type 为multipart/form-data
,Spring 后台会自动装配,类似于正常的 POST 请求。所以实体类就不需要加 json 注解
@RequestBody
了,去掉就行了。这样:
只要前台传过来的属性和
User
实体字段对应上,就可以自动映射好。