Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primefaces File Download not working?

Tags:

jsf

primefaces

Trying to get a simple file download working and all I am getting is a hanging AJAX status bar and that's it. My backing bean outputs render the correct name on the prep and the download.

Am I doing this wrong? both outputs seem to me to be correct.

JSF 2.0 Primefaces 3.4

        <h:form>
            <p:commandButton id="downloadLink" value="Download" actionListener="#{filemanagement.prepDownload}"> 
                <p:fileDownload value="#{filemanagement.download}" />
            </p:commandButton>
        </h:form>

Backing bean:

private DefaultStreamedContent download;

public void setDownload(DefaultStreamedContent download) {
    this.download = download;
}

public DefaultStreamedContent getDownload() throws Exception {
    System.out.println("GET = " + download.getName());
    return download;
}

public void prepDownload() throws Exception {
    File file = new File("C:\\file.csv");
    InputStream input = new FileInputStream(file);
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
    System.out.println("PREP = " + download.getName());
}
like image 551
user2124871 Avatar asked Apr 18 '13 21:04

user2124871


2 Answers

Guide for Primefaces version >= 10:

For Primefaces versions before 10 you had to disable ajax on the commandButton with ajax=false.

Since version 10 that's no longer needed, see Primefaces Documentation 10.

Guide for Primefaces version < 10:

See Primefaces Documentation 6.2

If you’d like to use PrimeFaces commandButton and commandLink, disable ajax option as fileDownload requires a full page refresh to present the file.

<h:form>
  <p:commandButton id="downloadLink" value="Download" ajax="false" actionListener="#{filemanagement.prepDownload}">
    <p:fileDownload value="#{filemanagement.download}" />
  </p:commandButton>
</h:form>
like image 171
Manuel Avatar answered Sep 19 '22 14:09

Manuel


Inside command button, set ajax=false and do not use action or action listener for commandlink.

<h:form>
  <p:commandButton id="downloadLink" value="Download" ajax="false">
    <p:fileDownload value="#{filemanagement.downloadValue}" />
  </p:commandButton>
</h:form>

Bean:

public StreamedContent getDownloadValue() throws Exception {
    StreamedContent download=new DefaultStreamedContent();
    File file = new File("C:\\file.csv");
    InputStream input = new FileInputStream(file);
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    download = new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
    System.out.println("PREP = " + download.getName());
    return download;
}
like image 28
Manbumihu Manavan Avatar answered Sep 18 '22 14:09

Manbumihu Manavan