Spring Boot基于OpenAPI3.0实现带元数据的multipart文件下载406错误排查
Swagger 3.0文件下载接口返回406问题排查
基于OpenAPI 3.0(Swagger 3.0)Schema定义实现文件下载功能时,调用接口始终触发406 Not Acceptable错误,相关实现信息如下:
原始Swagger Schema定义
"get": { "operationId": "getAttachment", "summary": "Retrieve attachments to a existing Ticket", "tags": [ "changeRequest" ], "parameters": [ { "required": true, "name": "id", "in": "path", "description": "Identifier of the Change Request", "schema": { "type": "string" } } ], "responses": { "200": { "description": "Ok", "headers": { }, "content": { "multipart/form-data": { "schema": { "type": "object", "properties": { "metadata": { "$ref": "#/components/schemas/Attachment" }, "file": { "type": "string", "format": "binary", "description": "Actual File Attachment" } } } } } } } }
通过Swagger代码生成插件构建项目时,自动生成的响应类如下:
public class InlineResponse200 { @JsonProperty("metadata") private Attachment metadata = null; @JsonProperty("file") private Resource file; }
对应的接口实现代码:
@ApiOperation(value = "Retrieve attachments to a existing Ticket", nickname = "getAttachment", notes = "", response = InlineResponse200.class, tags={ "changeRequest"}) @RequestMapping(value = "/changeRequest/attachment/{id}", produces = { "multipart/form-data", "application/json" }, method = RequestMethod.GET) public ResponseEntity<InlineResponse200> getAttachment(@PathVariable("id") String id) { Attachment lAttachmentMetadata = new Attachment(); lAttachmentMetadata.setDescription("This is a sample description"); lAttachmentMetadata.setSize(2000); FileSystemResource fileSysResource = new FileSystemResource(new File("C:\\Projects\\Service Assurance\\Chnage Mgmt\\Attachments\\attachment.txt")); InlineResponse200 responseObject = new InlineResponse200(); responseObject.setFile(fileSysResource); responseObject.setMetadata(lAttachmentMetadata); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileSysResource.getFilename() + "\"") .header("Content-Type", "multipart/form-data") .body(responseObject); }
调用接口时的报错日志:
Thu Oct 15 03:46:39 IST 2020:DEBUG:<< "{"timestamp":"2020-10-14T22:16:39.258Z","status":406,"error":"Not Acceptable","message":"Could not find acceptable representation","path":"/changeManagement/api/v1/changeRequest/attachment/1234"}"
在SOAPUI中测试接口同样返回406状态,无正常业务响应体。
错误根因
406错误的触发逻辑非常直接:Spring MVC会按照请求Accept头、接口produces声明的内容类型、已注册的HttpMessageConverter支持的序列化格式三者做匹配,只要找不到能满足匹配要求的序列化器,就会抛出"Could not find acceptable representation"的406异常。结合代码来看,问题出在两个核心认知偏差上:
- 对Spring内置Multipart组件的能力有误解:Spring里的Multipart相关转换器,从设计上就只用来解析客户端发上来的multipart/form-data格式的请求入参,根本不支持把服务端返回的普通Java对象序列化回multipart格式的响应流。现在把InlineResponse200这个普通POJO当响应体,接口又声明要返回multipart/form-data,Spring翻遍所有内置转换器都找不到能处理这个格式的组件,自然直接报406。
- 手动设置响应头的操作无效:在返回值里手动加了
Content-Type: multipart/form-data头,但实际响应体还是Spring序列化的JSON结构,头声明的内容类型和实际返回的内容完全对不上,就算绕过了转换器匹配,客户端也没法正确解析。
对应解决方案
根据业务需求二选一即可:
方案1:采用常规单文件下载实现(推荐)
这是生产环境单文件下载最常用的实现方式,不需要额外引入依赖,也不会踩序列化的坑:
- 调整OpenAPI Schema定义:将200响应的content格式从
multipart/form-data改为application/octet-stream,schema定义为type: string, format: binary;附件元信息可以通过自定义响应头传递(比如X-Attachment-Description、X-Attachment-Size)。 - 调整接口实现:直接返回
ResponseEntity<Resource>类型,不再构造嵌套的POJO响应类,示例代码:
@ApiOperation(value = "Retrieve attachments to a existing Ticket", nickname = "getAttachment", response = Resource.class, tags={ "changeRequest"}) @RequestMapping(value = "/changeRequest/attachment/{id}", produces = { "application/octet-stream" }, method = RequestMethod.GET) public ResponseEntity<Resource> getAttachment(@PathVariable("id") String id) { // 读取附件元数据 String desc = "This is a sample description"; Long fileSize = 2000L; FileSystemResource fileSysResource = new FileSystemResource(new File("C:\\Projects\\Service Assurance\\Chnage Mgmt\\Attachments\\attachment.txt")); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileSysResource.getFilename() + "\"") .header("X-Attachment-Description", desc) .header("X-Attachment-Size", fileSize.toString()) .contentLength(fileSize) .body(fileSysResource); }
方案2:确需返回multipart/form-data格式响应
如果业务上必须返回带元数据的multipart结构,不能直接将普通POJO交给Spring自动序列化:
- 移除
produces声明中的application/json,避免Spring优先尝试JSON转换器造成匹配失败。 - 手动按照RFC规范构造multipart响应流,通过
ByteArrayResource拼装各段的边界、内容头、二进制内容,最后设置带正确边界值的Content-Type头。 - 也可以通过自定义
MultipartHttpMessageConverter注册到Spring转换器链,开启响应侧的multipart序列化能力,注意调整转换器优先级,避免覆盖默认的JSON序列化逻辑。
附加排查点
- 检查请求侧的
Accept头:如果测试工具默认发送Accept: application/json,但接口仅声明支持multipart格式,也会触发406,需确保请求头和接口produces声明的格式一致。 - 不要手动覆盖响应的
Content-Type头,优先让Spring根据返回值类型和produces的定义自动匹配对应转换器,避免头信息和实际响应体不匹配。
内容的提问来源于stack exchange,提问作者Nikhil K
相关产品推荐
相关产品推荐

