Thursday, June 28, 2012

How to Download File using JSF

Following is the simple example how to download file from Server using JSF application

1. Create new JSF bean, either ManageBean or Component Bean using Spring framework

1:  package com.jsf.app.managedbean;  
2:  import java.io.BufferedInputStream;  
3:  import java.io.BufferedOutputStream;  
4:  import java.io.File;  
5:  import java.io.FileInputStream;  
6:  import java.io.IOException;  
7:  import javax.faces.context.FacesContext;  
8:  import javax.servlet.http.HttpServletResponse;  
9:  import javax.faces.bean.ManagedBean;  
10:  @ManagedBean(name="fileDownloadBean")  
11:  public class FileDownloadBean {  
12:       private static final int DEFAULT_BUFFER_SIZE = 10240;  
13:       private String filePath = "c:\\download\\test.txt";  
14:       public void downLoad() throws IOException {  
15:            FacesContext context = FacesContext.getCurrentInstance();  
16:            HttpServletResponse response = (HttpServletResponse) context  
17:                      .getExternalContext().getResponse();  
18:            File file = new File(filePath);  
19:            if (!file.exists()) {  
20:                 response.sendError(HttpServletResponse.SC_NOT_FOUND);  
21:                 return;  
22:            }  
23:            response.reset();  
24:            response.setBufferSize(DEFAULT_BUFFER_SIZE);  
25:            response.setContentType("application/octet-stream");  
26:            response.setHeader("Content-Length", String.valueOf(file.length()));  
27:            response.setHeader("Content-Disposition", "attachment;filename=\""  
28:                      + file.getName() + "\"");  
29:            BufferedInputStream input = null;  
30:            BufferedOutputStream output = null;  
31:            try {  
32:                 input = new BufferedInputStream(new FileInputStream(file),  
33:                           DEFAULT_BUFFER_SIZE);  
34:                 output = new BufferedOutputStream(response.getOutputStream(),  
35:                           DEFAULT_BUFFER_SIZE);  
36:                 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];  
37:                 int length;  
38:                 while ((length = input.read(buffer)) > 0) {  
39:                      output.write(buffer, 0, length);  
40:                 }  
41:            } finally {  
42:                 input.close();  
43:                 output.close();  
44:            }  
45:            context.responseComplete();  
46:       }  
47:  }  

2. Now Access the file using the JSF link as shown below:

1:                      <h:form>  
2:                           <h:commandLink id="getDownload" value="Download Files"  
3:                                     action="#{fileDownloadBean.downLoad}">  
4:                                </h:commandLink>  
5:                      </h:form>  

3. Create web.xml something like:
1:  <?xml version="1.0" encoding="UTF-8"?>  
2:  <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
3:       xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
4:       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
5:       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
6:       id="WebApp_ID" version="2.5">  
7:       <listener>  
8:            <listener-class>com.sun.faces.config.ConfigureListener</listener-class>  
9:       </listener>  
10:       <context-param>  
11:            <param-name>javax.faces.PROJECT_STAGE</param-name>  
12:            <param-value>Development</param-value>  
13:       </context-param>  
14:       <context-param>  
15:            <param-name>javax.faces.CONFIG-FILES</param-name>  
16:            <param-value>WEB-INF/faces-config.xml</param-value>  
17:       </context-param>  
18:       <context-param>  
19:            <param-name>com.sun.faces.expressionFactory</param-name>  
20:            <param-value>com.sun.el.ExpressionFactoryImpl</param-value>  
21:       </context-param>  
22:       <servlet>  
23:            <servlet-name>Faces Servlet</servlet-name>  
24:            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>  
25:            <load-on-startup>1</load-on-startup>  
26:       </servlet>  
27:       <servlet-mapping>  
28:            <servlet-name>Faces Servlet</servlet-name>  
29:            <url-pattern>/faces/*</url-pattern>  
30:       </servlet-mapping>  
31:       <servlet-mapping>  
32:            <servlet-name>Faces Servlet</servlet-name>  
33:            <url-pattern>*.jsf</url-pattern>  
34:       </servlet-mapping>  
35:       <servlet-mapping>  
36:            <servlet-name>Faces Servlet</servlet-name>  
37:            <url-pattern>*.faces</url-pattern>  
38:       </servlet-mapping>  
39:       <servlet-mapping>  
40:            <servlet-name>Faces Servlet</servlet-name>  
41:            <url-pattern>*.xhtml</url-pattern>  
42:       </servlet-mapping>  
43:  </web-app>  

Now after deploying this in the servlets container, you will see the dialog box for Save the File/Open.


9 comments:

  1. Thank you so much! Tried so many things, and it finally worked with your solution

    ReplyDelete
  2. This is awesome, thanks for such a good example.

    ReplyDelete
  3. It didn't work 4r me.The same page is getting displayed on clicking d hyperlink when i am using h:commandLink without surrounding it with h:form.When i am using h:commandLink inside h:form,the page keeps on displaying loading.I am using JSF 1.2.Pls help me soon.

    ReplyDelete
  4. Thank You so much it works like a charm :)

    ReplyDelete