p:调用fileDownload bean方法但不显示文件下载

Kis*_*ash 4 jsf download primefaces

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

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

此操作的主要思想是让用户上传文件并为上传的文件生成下载链接,以便他可以在提交前下载并查看.

这是我的代码:

的index.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>
Run Code Online (Sandbox Code Playgroud)

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;
    }
Run Code Online (Sandbox Code Playgroud)

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

java.lang.IllegalStateException: getOutputStream() has already been called for this response
Run Code Online (Sandbox Code Playgroud)

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

如果我的技术或代码错了,请纠正我,如果你知道,请提出更好的建议.

Bal*_*usC 12

<p:commandLink>由火灾默认Ajax请求.您无法通过ajax下载文件.负责处理ajax请求的JavaScript不知道如何处理检索到的二进制文件,这与预期的XML响应完全不同.出于明显的安全原因,JavaScript无法触发具有任意内容的" 另存为"对话框.

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

<p:commandLink ajax="false">
Run Code Online (Sandbox Code Playgroud)

要不就

<h:commandLink>
Run Code Online (Sandbox Code Playgroud)

也可以看看: