Downloading file in JSF 2

Here is a simple sample code to downloads a file in jsf 2.x.

Inside your Form Bean you write a method that basically either reads a file from file system or creates it dynamically and writes the file to HttpServletResponse instance obtained using FacesContext.getCurrentInstance().getExternalContext().getResponse();


@ManagedBean(name = "formBean")
@SessionScoped
public class FormBean implements Serializable
{
  private static final long serialVersionUID = 1L;

  /**
   * Download file.
   */
  public void downloadFile() throws IOException
  {
     File file = new File("C:\\docs\\instructions.txt");
     InputStream fis = new FileInputStream(file);
     byte[] buf = new byte[1024];
     int offset = 0;
     int numRead = 0;
     while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length - offset)) >= 0)) 
     {
       offset += numRead;
     }
     fis.close();
     HttpServletResponse response =
        (HttpServletResponse) FacesContext.getCurrentInstance()
            .getExternalContext().getResponse();
   
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=instructions.txt");
    response.getOutputStream().write(buf);
    response.getOutputStream().flush();
    response.getOutputStream().close();
    FacesContext.getCurrentInstance().responseComplete();
  }
}
Advertisements

  1. #1 by TungPhien on May 3, 2013 - 3:23 am

    Hi Administrator, When i use your code, i see a error “com.liferay.portlet.ResourceResponseImpl cannot be cast to javax.servlet.http.HttpServletResponse”.
    – Can you help me ?

    • #2 by dorra on July 8, 2013 - 3:17 pm

      please i want to download excel file

  2. #3 by bhaumik on May 30, 2013 - 12:56 pm

    whats is FacesContext???

  3. #4 by Yuriy on September 2, 2013 - 11:23 am

    code works fine! thank you

  4. #5 by pradip garala on February 28, 2014 - 12:34 pm

    it was nice example, really helpful

  5. #6 by Ft Lemm Lu on May 22, 2014 - 1:38 pm

    thanks but work just with .txt

  6. #7 by Dinesh on September 1, 2016 - 7:36 am

    Thankk you it is working

  7. #8 by Diamond City West on August 26, 2017 - 1:23 pm

    Hello Bharat,
    Can I show success message in ui, once the file download is completed and for that what should I do apart from adding message in faces context add message method.
    Thanks and Regards’
    Ajit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: