Spring Boot返回带有ResponseEntity <resource>的application / pdf

时间:2018-11-02 14:11:45

标签: rest spring-boot pdf

在我的springboot应用程序中,我尝试返回带有ResponseEntity-Resource-的pdf文件来模拟服务。因此,我无法更改此方法的返回类型。

我的代码:

@RequestMapping(
        value = "/pdf",
        produces = MediaType.APPLICATION_PDF_VALUE,
        method = RequestMethod.GET
)
public ResponseEntity<Resource> getpdf() {
    try {
        ClassPathResource pdfFile = new ClassPathResource("sample.pdf");

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT");
        headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
        headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
        headers.add(HttpHeaders.PRAGMA, "no-cache");
        headers.add(HttpHeaders.EXPIRES, "0");
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + pdfFile.getFilename());
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

        log.info("pdfFile.contentLength() : " + pdfFile.contentLength());

        return ResponseEntity
                .ok()
                .headers(headers)
                //.contentLength(pdfFile.contentLength())
                //.contentType(MediaType.APPLICATION_PDF)
                .body(new InputStreamResource(pdfFile.getInputStream()));
    } catch (IOException e) {
        log.error("Couldn't serialize response for content type ", e);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

当我尝试用邮递员或招摇来称呼它时,我得到一个带有响应头的406:

{   
"date": "Fri, 02 Nov 2018 14:04:44 GMT",   
"content-length": "0", 
"content-type": null 
}

有人有主意吗?

Swagger response

2 个答案:

答案 0 :(得分:0)

您可以删除produces = MediaType.APPLICATION_PDF_VALUE

在RequestMapping中无需添加produces = MediaType.APPLICATION_PDF_VALUE,,因为它似乎试图在内部转换ResponeBody。

下面的代码行已经足够了。

headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

答案 1 :(得分:0)

太复杂了..下载文件要容易得多

@GetMapping(value="printing/",produces= MediaType.APPLICATION_PDF_VALUE)
public  @ResponseBody byte[]  print(@RequestParam("filterParam") String filterParam) {

    try {
        FileInputStream fis= new FileInputStream(new File("path to your file"));
        byte[] targetArray = new byte[fis.available()];
        fis.read(targetArray);
        return targetArray;
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}