【问题标题】:Primefaces Download File Which is Outside FacesContextPrimefaces 下载 FacesContext 之外的文件
【发布时间】:2015-11-18 14:55:56
【问题描述】:

我正在将 Excel 工作簿上传到应用程序上下文之外的目录(出于备份目的)并将其路径保存到数据库中。

现在我需要下载该文件并且我正在尝试使用 Primefaces 下载,但我得到了一个 null 文件

这是我的代码(很像 Primefaces Showcase 下载部分):

豆子:

private StreamedContent file;

public void download(Arquivo arquivo) throws IOException {
    InputStream stream = ((ServletContext)FacesContext.getCurrentInstance()
      .getExternalContext().getContext()).getResourceAsStream(arquivo.getNomeArquivo());

    file = new DefaultStreamedContent(stream);
}

查看:

<h:commandLink id="btnDownload" title="Download Arquivo" 
  actionListener="#{arquivoBean.download(obj)}">
    <p:fileDownload value="#{arquivoBean.file}" />
</h:commandLink>

基本上我需要将外部路径传递给 InputStream 而不是 FacesContext。

据我所知,我的问题是我将应用程序上下文传递给 InputStream,将路径附加到 getResourceAsStream 的参数中,当然,找不到。

我是 FileDownload 的新手。提前致谢!

【问题讨论】:

  • 只根据路径创建一个文件输入流..?在 JSF 支持 bean 类中访问本地磁盘文件系统与在常规 Java 应用程序类中没有什么不同。 JSF 和 &lt;p:fileDownload&gt; 都不关心您如何创建 InputStream 实例,只要它是 InputStream 的实例即可。
  • 我试过这样做: InputStream stream = new FileInputStream(arquivo.getNomeArquivo());文件 = 新的 DefaultStreamedContent(流);但现在我得到了一个 null.txt 文件。
  • 所以文件内容都很好,只有文件名不是吗?您确实没有在DefaultStreamedContent 的任何地方指定文件名。您只指定了文件内容。

标签: java excel jsf-2 primefaces download


【解决方案1】:

如果它仍然有用:

StreamedContent streamToReturn = DefaultStreamedContent.builder().name(FILE_NAME).contentType( FacesContext.getCurrentInstance().getExternalContext()
            .getMimeType(FILE_PATH))
            .stream(() -> {
                try {
                    return new FileInputStream(FILE_PATH);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                }
            }).build();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 2012-05-18
    • 2013-04-12
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多