0
1

I want to provide one or more files for my users to download it from a user dialog in JSF, how can I do that?

asked 09.10.2013 at 12:25

SupportIvyTeam's gravatar image

SupportIvyTeam ♦♦
1.4k102118122
accept rate: 77%


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.

link

answered 09.10.2013 at 12:39

SupportIvyTeam's gravatar image

SupportIvyTeam ♦♦
1.4k102118122
accept rate: 77%

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×58
×51

Asked: 09.10.2013 at 12:25

Seen: 10,598 times

Last updated: 09.10.2013 at 12:39