【问题标题】:read and open PDF in a new browser window with JSF使用 JSF 在新的浏览器窗口中阅读和打开 PDF
【发布时间】:2014-04-01 23:04:11
【问题描述】:

Java/JSF

我尝试在 新的浏览器窗口 中打开 PDF,而不是下载它,但在每次尝试中,文件都会成功下载,并且会在应用程序中打开一个新标签只有pdf文件,而不是pdf文件。

<p:commandLink title="report" target="_blank"
    action="#{managedBean.generateReport('P',true)}"
    ajax="false" immediate="false" >
</p:commandLink>

托管 bean:generateReport 调用 downloadFile

下面的filePath参数= /temp/doc/abc.pdf (chmod 777)

public static void downloadFile(String filePath) throws IOException{
    FacesContext context = FacesContext.getCurrentInstance();  
    HttpServletResponse response = (HttpServletResponse) context  
                         .getExternalContext().getResponse();  
    File file = new File(filePath);  
    if (!file.exists()) {  
      response.sendError(HttpServletResponse.SC_NOT_FOUND);  
      return;  
     }  
    response.reset();  
    response.setBufferSize(DEFAULT_BUFFER_SIZE);  
    response.setContentType("application/octet-stream");  
    response.setHeader("Content-Length", String.valueOf(file.length()));  
    response.setHeader("Content-Disposition", "attachment;filename=\""  
           + file.getName() + "\"");  
    BufferedInputStream input = null;  
    BufferedOutputStream output = null;  

    try 
    {  
        input = new BufferedInputStream(new FileInputStream(file),  
                    DEFAULT_BUFFER_SIZE);  
        output = new BufferedOutputStream(response.getOutputStream(),  
                        DEFAULT_BUFFER_SIZE);  
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
        int length;  
        while ((length = input.read(buffer)) > 0) {  
            output.write(buffer, 0, length);  
        }  
    } finally 
    {  
        input.close();  
        output.close();  
    }  
    context.responseComplete();
}

我的 Chromium 插件已启用:

【问题讨论】:

  • 怎么样?
  • 你试过Content-Disposition:inline吗?
  • 试过 ..:inline 没用

标签: java jsf primefaces downloadfile


【解决方案1】:

primefaces media 怎么样:

来自showcase

<p:media value="/resources/other/guide.pdf" width="100%" height="300px"/>  

您也可以将此 PDF 查看器放入 p:dialog here

【讨论】:

  • 好主意,我用 p:media 和复合对话框实现了。请记住 p:media 不适用于 @ViewScoped。
  • 如果客户端在运行时生成报告而不是将其保存在文件系统上会怎样
【解决方案2】:

如果您希望浏览器知道它是 PDF,则必须将其设置为 PDF 内容类型(“application/pdf”)。您将其设置为“application/octet-stream”。

【讨论】:

  • 从浏览器检查标题。如果安装的 PDF 插件没有加载它,因为浏览器不知道文件 MIME 类型。还。您是否在文件名值上添加了 .PDF 扩展名?
【解决方案3】:

在这一行

response.setHeader("Content-Disposition", "attachment;filename=\""  + file.getName() + "\"");

替换为

response.setHeader("Content-Disposition", "filename=\""  + file.getName() + "\""); 

删除 ==> 附件;然后 Pdf 将在新标签页中打开

【讨论】:

  • 为什么 OP 应该这样做?请解释你的答案。
  • 您自己做过/尝试过吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 1970-01-01
  • 2017-11-22
相关资源
最近更新 更多