PrimeFaces offers the p:fileDownload
widget for this purpose, it allows to use (File)InputStream
for download.
You need a p:commandButton
(or alternatively a p:commandLink
) to work with the p:fileDownload
. It is important to set the attribute ajax
to false
as files cannot be downloaded by AJAX.
<p:commandButton value="Download" actionListener="#{logic.download}" ajax="false">
<p:fileDownload value="#{data.file}"></p:fileDownload>
</p:commandButton>
The attribute value
points to a member of the process data class that must have the type org.primefaces.model.StreamedContent
. This object will be the one downloaded. In the code snippet below you can see how you can setup this object in the logic of the Html User Dialog.
import org.primefaces.model.DefaultStreamedContent;
import java.io.FileInputStream;
// create temp file and add some content
File file = new File("mytemp." + System.currentTimeMillis() + ".txt", true);
file.createNewFile();
file.write("Hallo " + System.currentTimeMillis());
// set file to download
FileInputStream fis = new FileInputStream(file.getJavaFile());
in.file = new DefaultStreamedContent(fis, "text/plain", file.getName());
We use DefaultStreamedContent
to set in the process data that then will be used by the p:fileDownload
. Note that the FileInputStream
is not closed. Doing that would automatically abort the download. To avoid memory leaks, the DefaultStreamedContent
will call the close
method.
For more information, please see the example project or have a look at the PrimeFaces FileDownload demo.
Note: This question and answer was originally posted by Heinrich Spreiter on his Xpert.ivy Hacker blog. Henry, many thanks to you for your enthusiastic work.
answered
09.10.2013 at 12:39
SupportIvyTeam ♦♦
1.4k●102●118●122
accept rate:
77%