Primefaces File Download not working?

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>

From PrimeFaces 10 and up you can use Ajax downloads!

https://primefaces.github.io/primefaces/10_0_0/#/components/filedownload?id=ajax-downloading

The download will be triggered by JavaScript when you use Ajax on your command button or link.

See also:

https://github.com/primefaces/primefaces/issues/5978


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

Tags:

Jsf

Primefaces