Saturday, June 12, 2010

Bit #19 - Downloading a file

Use an af:fileDownloadActionListener Rich Faces component to download data from the server to a client machine. Add the listener inside the component that will initiate the download, an af:commandButton for example, and specify the content type and the name of the file. Also specify a method in a backing bean that will be called to perform the download. In the backing bean method get the formated data to be saved from the model and use the supplied OutputStream to write the data.


In .jsf page:

<af:commandbutton id="buttonid"  " text="Download" ...
    <af:filedownloadactionlistener contenttype="application/octet-stream"
                method="#{backingBean.doDownload}"  filename="defaultFilename.txt"/>          

In backing bean:

  public void doDownload(FacesContext facesContext, OutputStream outputStream) {
      // write the neccessary code to get the download data from the Model
      String data = getDownloadData();

      // save to the output stream
      try {
          OutputStreamWriter writer = new OutputStreamWriter(outputStream,"UTF-8");
      } catch (IOException e) {
          // handle I/O exceptions


JSF Page
Backing Bean


  1. What do if you want the doDownload to decide whether or not to send a PDF or Excel file, can one change the content type and filename of the fileDownloadActionListener in the doDownload?

  2. Could you present a choice list as part of your page for the user to select PDF or Excel? Then based on the user choice you do the appropriate download in the doDownload(). Same for the filename - the user could enter it as part of your page's UI. That means using bindings for the filename attribute instead of hardcoding it.

  3. how to set the file name dynamically from managed bean. its kind of static, but how can we change the file name from backend .


Related Posts Plugin for WordPress, Blogger...