Postman向Spring Boot上传Multipart文件失败,报406错误
解决Spring Boot文件上传接口返回406 Not Acceptable错误
问题场景
编写的Spring Boot文件上传接口代码如下:
@RequestMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.POST) @ResponseBody public FileResponse uploadFile(@RequestParam("file") MultipartFile file) { String name = storageService.store(file); String uri = ServletUriComponentsBuilder.fromCurrentContextPath() .path("/download/") .path(name) .toUriString(); return new FileResponse(name, uri, file.getContentType(), file.getSize()); }
通过Postman上传文件时,收到406错误响应:
{ "timestamp": "2022-09-12T12:42:46.493+00:00", "status": 406, "error": "Not Acceptable", "path": "/upload-file" }
错误原因
406 Not Acceptable 错误的核心是服务器无法生成客户端请求头Accept中指定格式的响应。你的接口返回FileResponse对象,Spring默认会尝试将其序列化为JSON格式,但以下情况会触发该错误:
- Postman的请求头
Accept字段设置了服务器不支持的类型(比如text/html、application/xml等); - 项目缺少JSON序列化依赖,导致Spring无法将对象转换为JSON响应;
- 接口未明确指定响应格式,内容协商过程中匹配不到合适的类型。
解决方案
- 调整Postman的Accept请求头:将
Accept字段设置为application/json,或者保留默认的*/*(表示接受任意格式),确保服务器能返回匹配的响应类型。 - 确认JSON序列化依赖:如果使用Spring Boot Web Starter,默认已包含Jackson依赖用于JSON序列化。若手动移除过,需重新添加:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> </dependency> - 显式指定接口响应格式:在
@RequestMapping注解中添加produces = MediaType.APPLICATION_JSON_VALUE,明确告知服务器返回JSON格式,避免内容协商冲突:@RequestMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public FileResponse uploadFile(@RequestParam("file") MultipartFile file) { // 原有业务代码 }
内容的提问来源于stack exchange,提问作者Nikita Zakharov
相关产品推荐
相关产品推荐

