我遇到一个有用的PDF生成代码,以便在
Spring MVC应用程序(
“Return generated PDF using Spring MVC“)中向客户端显示文件:
@RequestMapping(value = "/form/pdf",produces = "application/pdf") public ResponseEntity<byte[]> 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<byte[]> response = new ResponseEntity<byte[]>( pdfContents,headers,HttpStatus.OK); return response; }
我添加了一个声明,该方法返回一个PDF文件(“Spring 3.0 Java REST return PDF document“):produce =“application / pdf”.
我的问题是,当上面的代码执行时,它立即要求客户端保存PDF文件.我希望在浏览器中首先查看PDF文件,以便客户端可以决定是否保存.
我发现“How to get PDF content (served from a Spring MVC controller method) to appear in a new window“建议在Spring表单标签中添加target =“_ blank”.我测试了它,并按预期,它显示一个新的选项卡,但保存提示出现了.
另一个是“I can’t open a .pdf in my browser by Java“的方法来添加httpServletResponse.setHeader(“Content-Disposition”,“inline”);但是我不使用HttpServletRequest来提供我的PDF文件.
@H_301_14@解决方法
尝试
httpServletResponse.setHeader("Content-Disposition","inline");
但是使用responseEntity如下.
HttpHeaders headers = new HttpHeaders(); headers.add("content-disposition","attachment; filename=" + fileName) ResponseEntity<byte[]> response = new ResponseEntity<byte[]>( pdfContents,HttpStatus.OK);
它应该工作
不知道这个,但是似乎你使用的是不好的setContentDispositionFormData,尝试>
headers.setContentDispositionFormData("attachment",fileName);
让我知道如果这样工作
UPDATE
This behavior depends on the browser and the file you are trying to
serve. With inline,the browser will try to open the file within the
browser.
headers.setContentDispositionFormData("inline",fileName);
要么
headers.add("content-disposition","inline;filename=" + fileName)
阅读这个知道差异between inline and attachment
@H_301_14@ @H_301_14@ 原文链接:https://www.f2er.com/java/126290.html