加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 在新的浏览器选项卡中打开ResponseEntity PDF

发布时间:2020-12-15 00:47:54 所属栏目:Java 来源:网络整理
导读:我遇到一个有用的PDF生成代码,以便在 Spring MVC应用程序( “ Return generated PDF using Spring MVC “)中向客户端显示文件: @RequestMapping(value = "/form/pdf",produces = "application/pdf")public ResponseEntitybyte[] showPdf(DomainModel domain
我遇到一个有用的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文件.

我的代码/情况如何在新的选项卡中打开PDF文件?

解决方法

尝试
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读