4

您好,我正在使用 JSF 和 Primefaces 进行文件上传和下载相同的文件操作。

我正在使用来自不同论坛和博客的技术(BelusC 的博客和 Primefaces Showcase)。

这个操作的主要思想是让用户上传一个文件,并为上传的文件生成一个下载链接,以便他可以在提交之前下载并看到它。

这是我的代码:

索引.xhtml

<h:form>
    <p:fileUpload showButtons="false" label="Attach Refrral" 
        auto="true" fileUploadListener="#{fileBean.uploadListener}"/>
</h:form>

<h:form >
   <p:commandLink>
      See Uploaded File
      <p:fileDownload value="#{fileBean.refrralFile}"/>
   </p:commandLink>
</h:form>

FileBean.java

private StreamedContent refrralFile;


    public void uploadListener(FileUploadEvent evt)throws Exception
    {
        UploadedFile fx = evt.getFile();

        File mainDir = new File("C:/","fileStorage");
        if(!mainDir.exists())
        {
            mainDir.mkdir();
        }
        File subDir = new File(mainDir,"AttachedRefrrals");
        if(!subDir.exists())
        {
            subDir.mkdir();
        }
        String fileName = fx.getFileName();

        File f = new File(subDir,fileName);
        FileOutputStream fos = new FileOutputStream(f);
        IOUtils.copy(fx.getInputstream(), fos);

        InputStream is = ((ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext()).getResourceAsStream(f.getAbsolutePath());
        refrralFile  = new DefaultStreamedContent(is, new MimetypesFileTypeMap().getContentType(f), fileName);

    }


    public StreamedContent getRefrralFile() {
        return refrralFile;
    }

使用上面的代码文件上传成功但是如果我点击文件下载链接ths抛出异常:

java.lang.IllegalStateException: getOutputStream() has already been called for this response

我使用了FacesContext#responseComplete(),因为它被建议很多地方,现在下载链接根本不起作用。

如果我的技术或代码有误,请纠正我,如果您知道,请提出更好的方法。

4

1 回答 1

12

默认情况下<p:commandLink>会触发一个 ajax 请求。您无法通过 ajax 下载文件。负责处理 ajax 请求的 JavaScript 不知道如何处理与预期的 XML 响应完全不同的检索到的二进制文件。由于明显的安全原因,JavaScript 没有任何工具来触发与任意内容的另存为对话。

因此,要解决您的具体问题,请使用

<p:commandLink ajax="false">

要不就

<h:commandLink>

也可以看看:

于 2013-04-10T12:10:21.743 回答