如何在Swagger上记录生成文件(pdf)以供下载的API?

时间:2018-01-31 15:47:58

标签: spring rest api swagger

我正在尝试发现一种记录返回PDF(或任何其他文件)的API的方法。

使用Spring,我的Rest资源是这样的:

@Override
@GetMapping(produces = "application/pdf")
public ResponseEntity<InputStreamResource> find(
        @PathVariable long id
) {

    Result result = service.find(id);

    HttpHeaders headers = disableCache();

    return ResponseEntity
            .ok()
            .headers(headers)
            .contentLength(result.getSize())
            .contentType(MediaType.parseMediaType("application/pdf"))
            .body(new InputStreamResource(result.getFileInputStream()));
}

这适用于下载文件。但我不知道使用Swagger记录响应的良好做法。

实际上,我尝试使用Swagger注释:

@ApiOperation(value = "Some description")
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "Success.")
})
@ResponseStatus(HttpStatus.OK)
@GetMapping(produces = "application/pdf")
ResponseEntity<InputStreamResource> find(
        @PathVariable long id
);

但Swagger在Swagger-ui上返回InputStreamResource作为Json的内容,结果。

如何代表Swagger响应的文件下载?

2 个答案:

答案 0 :(得分:0)

让我们尝试像这样更新代码:

  1. 更新标题
        headers.add("Content-Type", "application/pdf");
        headers.add("Content-Disposition", "attachment; filename=report.pdf");
  1. @ApiResponses(value = {     @ApiResponse(代码= 200,消息=“成功。”,响应= byte.class ) })
  2. 更新pom:
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>

希望有帮助

答案 1 :(得分:0)

注释被忽略,但这对我有用:

TypeResolver typeResolver = new TypeResolver();
new Docket(DocumentationType.OAS_30)
    .alternateTypeRules(AlternateTypeRules.newRule(
        typeResolver.resolve(ResponseEntity.class, InputStreamResource.class),
        typeResolver.resolve(Byte.class), 
        DIRECT_SUBSTITUTION_RULE_ORDER));