Download File from FileSystem in JSF 2.0

Below method is to be called on <h:commandButton> or <h:commandLink> .

public void downloadDoc() {
        try {
            File file = new File("C:\\eGPDocs\\" + documents.getDocumentName());
            InputStream fis = new FileInputStream(file);
            byte[] buf = new byte[Integer.valueOf(documents.getDocumentSize())];
            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=" + documents.getDocumentName() + "");
            response.getOutputStream().write(buf);
            response.getOutputStream().flush();
            response.getOutputStream().close();
            FacesContext.getCurrentInstance().responseComplete();
        } catch (IOException ex) {
            System.out.println("Error : " + ex);
        }
    }
Advertisements
This entry was posted in JSF 2.0. Bookmark the permalink.

6 Responses to Download File from FileSystem in JSF 2.0

  1. Med says:

    Thanks! That was helpful. I was using some kind of work around, but your method seems to be smarter 🙂

  2. rakesh says:

    what is documents() here.

  3. rakesh says:

    what is documents() here

  4. rakesh says:

    i am unable to get documents.getDocumentSize().

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