SpringBoot REST结合Swagger/OpenAPI返回PDF二进制的正确方式及报错解决
SpringBoot REST 结合Swagger定义PDF二进制返回端点的解决方案
问题与解答
1. 内容类型注解是否需要同时使用?
是,两个注解各司其职:
@Produces("application/pdf"):属于Spring MVC注解,用于告知Spring该接口的响应媒体类型,是内容协商的核心配置。@ApiResponse(content = @Content(mediaType = "application/pdf", schema=@Schema(type="string", format="binary"))):属于Swagger/OpenAPI注解,仅用于生成API文档,让Swagger UI识别该接口返回二进制PDF数据,不影响Spring的请求处理逻辑。
2. 解决MessageBodyWriter not found错误
出现该错误是因为Spring没有内置针对application/pdf与byte[]/ByteArrayInputStream组合的消息转换器,最简洁的解决方案是返回ResponseEntity<Resource>:
import org.springframework.core.io.ByteArrayResource; import org.springframework.http.CacheControl; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; @RestController public class PdfDownloadController { @GetMapping("/pdf/download") @Produces("application/pdf") @Operation(summary = "下载PDF文件") @ApiResponse(responseCode = "200", content = @Content(mediaType = "application/pdf", schema = @Schema(type = "string", format = "binary"))) public ResponseEntity<ByteArrayResource> downloadPdf() { // 替换为你的PDF二进制数据生成逻辑 byte[] pdfContent = generatePdfContent(); ByteArrayResource resource = new ByteArrayResource(pdfContent); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_PDF) .cacheControl(CacheControl.noCache()) .header("Content-Disposition", "attachment; filename=\"sample.pdf\"") .body(resource); } private byte[] generatePdfContent() { // 示例:这里可以用iText、Apache PDFBox等库生成PDF return new byte[0]; } }
如果坚持使用byte[],可以自定义HttpMessageConverter,但Resource方案是Spring官方推荐的文件下载方式,无需额外配置。
3. 相关文档获取
- Spring MVC官方文档:重点查看内容协商和消息转换器章节,了解Spring如何处理响应类型。
- Swagger/OpenAPI官方文档:查阅
@ApiResponse、@Content注解的参数说明,明确二进制内容的schema配置规则。 - Spring Boot官方文档:搜索"RESTful Web Services"下的文件下载示例,有完整的实践指导。
内容的提问来源于stack exchange,提问作者evilfred
相关产品推荐
相关产品推荐

