无法从Chrome预览器下载PDF

时间:2019-02-20 12:55:58

标签: google-chrome pdf-viewer

我有一个Web应用程序,可将PDF输出到浏览器。预期的行为是,当我单击按钮时,将预览PDF,然后在单击下载按钮时-将下载。

下载按钮不起作用-单击该按钮时,它仅开始下载空文件,并失败,并显示“网络连接失败”消息。

另一方面,当我要“打印” PDF时,它也向我显示“保存”按钮,并且该按钮起作用了!

我尝试更改标头,服务器设置,感觉就像我尝试了一切...知道是什么原因吗?

奇怪的是-在Firefox和Internet Explorer中都可以使用

我的标题设置如下:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Disposition: inline; filename="file.pdf"
Content-Type: application/pdf
Date: Wed, 20 Feb 2019 12:38:27 GMT
Expires: 0
Pragma: no-cache
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
Transfer-Encoding: chunked
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

生成pdf的JAVA代码

String ctype = "pdf".equals(reportType) ? "application/pdf" : "text/html; charset=utf-8";
    String ext = "pdf".equals(reportType) ? "pdf" : "html";

    InputStream srcInput;
    try {
      String url = buildPath(....);
      srcInput = new URL(url).openStream();
    } catch (IOException ex) {
      ext = "txt";
      ctype = "text/plain; charset=utf-8";
      srcInput = new ByteArrayInputStream(("Load error: " + ex.getMessage()).getBytes());
    }

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
      // Open file.
      input = new BufferedInputStream(srcInput);

      // Init servlet response.
      response.reset();
      response.setHeader("Content-Type", ctype);
      //response.setHeader("Content-Length", String.valueOf(file.length()));
      String filename = "file.pdf";
      response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\"");
      output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);

      // Write file contents to response.
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int length;
      while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
      }

      // Finalize task.
      output.flush();

Download fails enter image description here

0 个答案:

没有答案