You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 23:31:00