Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

p:fileDownload bean method is invoked but file download does not show up

Hello I'm doing File upload and download same file operation using JSF and Primefaces.

I'm using techniques from different forums and blogs combined(BelusC 's blog and Primefaces Showcase).

The main idea of this operation is to let user to upload a file and generate a Download link for the uploaded file so that he can download and see it before Submitting.

Here is my code:

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>

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;
    }

Using above code File is uploading Successfully but if I click file download link ths throwing exception:

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

I used FacesContext#responseComplete(), as its been suggested many places, now download link is not working at all.

Please correct me if I'm wrong in my technique or code and suggest any better way if you know.

like image 845
Kishor Prakash Avatar asked Dec 15 '22 11:12

Kishor Prakash


1 Answers

The <p:commandLink> fires by default an ajax request. You can't download files via ajax. JavaScript, who's responsible for processing the ajax request, has no clue what to do with retrieved binary file which is quite different from the expected XML response. JavaScript has for obvious security reasons no facilities to trigger a Save As dialogue with arbitrary content.

So, to fix your concrete problem, use

<p:commandLink ajax="false">

or just

<h:commandLink>

See also:

  • How to provide a file download from a JSF backing bean?
  • PrimeFaces <p:fileDownload> showcase page - this also explicitly shows ajax="false"
like image 179
BalusC Avatar answered May 21 '23 02:05

BalusC