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());
}
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With