【问题标题】:produces = "application/pdf" not working on Spring Boot产生 =“应用程序/pdf”在 Spring Boot 上不起作用
【发布时间】:2016-11-12 15:34:29
【问题描述】:

我有 Spring Boot 项目,并且正在使用 Jasper Report。我发布了一些 json 数据和响应返回给我:

%PDF-1.5
%����
1 0 obj
<undefined</Filter/FlateDecode/Length 29>>stream
x�+�r
�26S�00SI�r
�
��13-
endstream
endobj
3 0 obj<undefined</Tabs/S/Group<undefined</S/Transparency/Type/Group/CS/DeviceRGB>>/Contents 1 0 R/Type/Page/Resources<undefined</ColorSpace<</CS/DeviceRGB>>/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]>>/Parent 2 0 R/MediaBox[0 0 595 842]>>
endobj
2 0 obj
<undefined</Kids[3 0 R]/Type/Pages/Count 1/ITXT(2.1.7)>>
endobj
4 0 obj<undefined</Type/Catalog/Pages 2 0 R/ViewerPreferences<undefined</PrintScaling/AppDefault>>>>
endobj
5 0 obj<undefined</ModDate(D:20160710203902+05'00')/Creator(JasperReports Library version 6.2.0)/CreationDate(D:20160710203902+05'00')/Producer(iText 2.1.7 by 1T3XT)>>
endobj
xref
0 6
0000000000 65535 f 
0000000015 00000 n 
0000000333 00000 n 
0000000110 00000 n 
0000000396 00000 n 
0000000487 00000 n 
trailer<undefined</Info 5 0 R/ID [undefined<07942c7c1b5b6068753ddc445ec60abf>undefined<c82bba08c068c3699915ac33668fef92>]/Root 4 0 R/Size 6>>
startxref
654
%%EOF

在我的休息控制器上,我添加到 RequestMapping 中产生 = "application/pdf" 但它不起作用。

@RequestMapping(value = "/gMapReports", method = RequestMethod.POST, produces = "application/pdf")
public ResponseEntity<InputStreamResource> gMapReports(@RequestBody GMapReportRequest gMapReportRequest) {

    return reportService.prepareResponse(reportService.gMapReports(gMapReportRequest));

}

我的prepareResponse方法:

public ResponseEntity<InputStreamResource> prepareResponse(File reportDocument) {
    FileInputStream fileInputStream = fileStreamConverter.getFileInputStream(reportDocument);

    return ResponseEntity
            .ok()
            .contentLength(reportDocument.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header("content-disposition", "filename=report")
            .body(new InputStreamResource(fileInputStream));
}

【问题讨论】:

  • 您将标头设置为八位字节流而不是 pdf,因此不确定您的期望。
  • 我刚刚解决了问题。我用邮递员测试过,邮递员不能下载文件,它显示PDF文件的输入流。我用 JS 脚本测试它是有效的。我也添加了标题“application/pdf”。坦克。

标签: java spring file spring-boot


【解决方案1】:

添加代码 produces = {"application/pdf"} 对我有用。完整示例:

@RequestMapping(value = "/pdfFile", method = RequestMethod.POST, produces = {"application/pdf"})
@ResponseBody
public FileSystemResource getFile(@ModelAttribute PdfFile pdfFile) {
    PdfFileGenerator pdfFileGenerator = new PdfFileGeneratorImpl();
    File file = pdfFileGenerator.generatePdf(pdfFile);
    return new FileSystemResource(file);
}

【讨论】:

    【解决方案2】:

    只是为了提出这个话题,如果有人到达这里时收到一个错误,即找不到适合 application/pdf 的转换器。
    检查您是否使用@RepositoryRestController 注释。
    如果是这种情况,请尝试切换到@RestController

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-15
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多