file downloading example of servlet

In this post, you will learn:

  • How to download a file using a servlet?
  • How to tell the browser that response is a file?
  • How to tell the file name to the browser?

Steps required for file downloading using a servlet?

File downloading is a two step process. In the first step, links of the files to be downloaded are obtained. In the second, a file is downloaded using the link. Both the steps require basic knowledge of Java input/output. The only important things are:

1. content type of the response need to be set to “application/x-download” in the servlet which writes the file contents to the output stream for downloading. This content type tells the browser that received response is a file which need to be saved on the client machine.

2.Content-Disposition header is set in the response having “attachment; filename=fname” value to tell the name of the downloaded file to the browser. Note that both of the content type and response header need to be set before the contents of the file are actually written to the output stream of the response.

Practical example of file downloading:

First, the index.html which contains a hyper link to submit request to the listFiles servlet.

 Obtain list of files to be downloaded

Second the ListFiles servlet. It reads the contents of the folder which contains files to be downloaded, creats a download link for each file and sends all the links as response to the client. This servlet assumes that the files to be downloaded are stored in a folder named uploads. This folder is under WEB-INF/classes.

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class ListFiles extends HttpServlet
{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
			 {
		
			
			PrintWriter out=response.getWriter();
			response.setContentType("text/html");
			out.println("Following files are available for download:<br/>");
			//obtain the path of the upload folder

			String path=getServletConfig().getServletContext().getRealPath("WEB-INF/classes/uploads");
			//Create a File object for the upload folder
			File file=new File(path);
			//Obtain list of items of the uploads folder
			String items[]=file.list();
			for(String item:items)
			{
				//For each item of the uploads folder, create a download link
				String filePath=path+File.separator+item;
				out.println("<a href=downloadFile?file="+filePath+">"+item+"</a><br/>");
				
			}
           	out.close();
			}
	}

Third the DownloadFile servlet. It receives the path of the file to be downloaded as request parameter. Reads the file contents and writes them to the response with proper content type and header so that the file can be saved on the client machine by the browser.

 package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class DownloadFile extends HttpServlet
{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
			 {
		
			//read the file path which is received as request parameter.
			String filePath=request.getParameter("file");
			//Create a File object for the file.
			File file=new File(filePath);
			
			//set contente type to be application/x-download to prevent the browser from rendering the contents.
			response.setContentType("application/x-download");
			 //set Content-Disposition header to suggest the file name to the browser.
	        response.setHeader("Content-Disposition", "attachment; filename=\""+file.getName()+"\"");
	        
			//An inputStream is created for the file.
			FileInputStream fis=new FileInputStream(file);
			//Size of the file is obtained
			int size=fis.available();
			
			//set content length equal to the file size.
	        response.setContentLength(size);
	        
			//A byte array equal to the file size is created.
			byte a[]=new byte[size];
			//All the file contents are read into the byte array.
			fis.read(a);
			//An output stream is created to write the file contents to the response
			ServletOutputStream out=response.getOutputStream();
			//byte array is written to the output stream
			out.write(a);
			
	       
	        //both the streams are closed.
			fis.close();
			out.close();
	         
           	
			}
	
	

}



Fourth, the web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  
 
  <servlet>
    <servlet-name>s1</servlet-name>
    <servlet-class>com.techmentro.learningpad.ListFiles</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>s1</servlet-name>
   <url-pattern>/listFiles</url-pattern>
  </servlet-mapping> 
  <servlet>
    <servlet-name>s2</servlet-name>
    <servlet-class>com.techmentro.learningpad.DownloadFile</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>s2</servlet-name>
   <url-pattern>/downloadFile</url-pattern>
  </servlet-mapping> 
  
</web-app>

Output screen images of the practical example:

This screen displays home page containing the hyperlink to obtain list of files to be downloaded.

[Not a valid template]

This screen displays the response of listFiles servlet. It contains the links of files to be downloaded.

[Not a valid template]

This screen represents the response of downloadFile servlet. It contains the file open/save dialog box presented by the browser for the downloaded file.

[Not a valid template]

Its time to recap the main concepts:

  1. File downloading is a two step process. In the first step, file link is obtained. In the second step, file is downloaded using the link.
  2. To download file, file contents are read by a servlet and stored in the output stream of the response.
  3. To tell the browser that the contents are not to be rendered but are saved on the client machine, content type is set to application/x-download.
  4. To provide the name of the downloaded file to the browser Content-Dispostion header is set in the response.
If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

One thought on “file downloading example of servlet

Leave a Reply

Your email address will not be published. Required fields are marked *