Search code examples
jsfprimefaces

Primefaces File Download not working?


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

Solution

  • Guide for Primefaces version >= 12.0.0

    Before PrimeFaces 11, you had to disable AJAX with DataExport. As of version 11 that's no longer needed.

    Primefaces Documentation 12.0.0

    Guide for Primefaces version >= 10 && < 12.0.0

    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>