在新的浏览器选项卡中打开ResponseEntity PDF
我遇到了一个有用的PDF生成代码,用于在Spring MVC应用程序中向客户端显示该文件( “ 使用Spring MVC返回生成的PDF ” ):
@RequestMapping(value = "/form/pdf", produces = "application/pdf") public ResponseEntity showPdf(DomainModel domain, ModelMap model) { createPdf(domain, model); Path path = Paths.get(PATH_FILE); byte[] pdfContents = null; try { pdfContents = Files.readAllBytes(path); } catch (IOException e) { e.printStackTrace(); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); String filename = NAME_PDF; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity response = new ResponseEntity( pdfContents, headers, HttpStatus.OK); return response; }
我添加了一个声明,该方法返回一个PDF文件( “ Spring 3.0 Java REST返回PDF文档 ” ): produces = "application/pdf"
。
我的问题是,当执行上面的代码时,它会立即要求客户端保存PDF文件。 我希望首先在浏览器中查看PDF文件,以便客户端可以决定是否保存。
我发现“ 如何获取PDF内容(从Spring MVC控制器方法提供)出现在新窗口中 ” ,建议在Spring表单标记中添加target="_blank"
。 我测试了它,正如预期的那样,它显示了一个新标签,但保存提示再次出现。
另一个是“ 我无法在我的浏览器中用Java打开.pdf ”的方法来添加httpServletResponse.setHeader("Content-Disposition", "inline");
但我不使用HttpServletRequest
来提供我的PDF文件。
在给出我的代码/情况的情况下,如何在新选项卡中打开PDF文件?
尝试
httpServletResponse.setHeader("Content-Disposition", "inline");
但是使用responseEntity如下。
HttpHeaders headers = new HttpHeaders(); headers.add("content-disposition", "attachment; filename=" + fileName) ResponseEntity response = new ResponseEntity( pdfContents, headers, HttpStatus.OK);
它应该工作
不确定这一点,但似乎你使用了不好的setContentDispositionFormData,尝试>
headers.setContentDispositionFormData("attachment", fileName);
如果有效,请告诉我
UPDATE
此行为取决于您尝试提供的浏览器和文件。 使用内联,浏览器将尝试在浏览器中打开文件。
headers.setContentDispositionFormData("inline", fileName);
要么
headers.add("content-disposition", "inline;filename=" + fileName)
阅读本文以了解内联和附件之间的区别
/* Here is a simple code that worked just fine to open pdf(byte stream) file * in browser , Assuming you have aa method yourService.getPdfContent() that * returns the bite stream for the pdf file */ @GET @Path("/download/") @Produces("application/pdf") public byte[] getDownload() { byte[] pdfContents = yourService.getPdfContent(); return pdfContents; }