从带有Swagger/OpenAPI注释的Springboot REST资源返回二进制PDF的正确方法是什么



如何定义一个REST端点,该端点使用带有Swagger注释的Java中的SpringBoot REST返回PDF二进制文件?

很多类似问题的答案都使用@RequestMapping,但我使用的是Swagger/OpenAPI注释,比如@ApiResponse。在我的资源方法上,我应该用2个注释来指示内容类型吗?

@ApiResponse(content = @Content(mediaType = "application/pdf", schema=@Schema(type="string", format="binary"))) 
@Produces("application/pdf")

当我尝试此操作并返回ResponseEntity<byte[]>或ResponseEntity<ByteArrayStream>像这样:

return ResponseEntity.ok()
.contentType(org.springframework.http.MediaType.APPLICATION_PDF)
.cacheControl(CacheControl.noCache())
.header("Content-Disposition", "attachment; filename=" + "blah.pdf")
.body(contents);

我得到错误:

MessageBodyWriter not found for media type=application/pdf

有什么地方可以找到这些东西的清晰文档吗?很难在谷歌上找到。

我发现;字节[]";from我的resource方法使它工作,或者一个原始的包含byte[]内容的Response。仍然奇怪的是,我无法让ResponseEntity工作。

ApiResponse中给出200responseCode怎么样?

@GetMapping(value = "/pdf-file", produces = MediaType.APPLICATION_PDF_VALUE)
@ApiResponse(content = @Content(schema = @Schema(type = "string", format = "binary")), responseCode = "200")
public ResponseEntity<byte[]> previewPerformanceReport(...

有点断章取义,但这是我的确切问题FWIW。

最新更新