File download example using servlet and jsp

Environment used:
JDK 1.8
Eclipse Luna
Web module 2.5
Tomcat 8(requires javax.servlet.3.1 jar)

Step 1:
Create an html file with a hyper link to download a file
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
	Click on the link to download:
	<a href="DownloadServlet">Download a File</a>

Step 2:
Create a Servlet program
1. Locate the file path
2. Set content type as APPLICATION/OCTET-STREAM
3. Set header as Content-Disposition 

Use attachment in header to download a file or set inline to view in browser
Refer Content-Disposition:


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		PrintWriter out = response.getWriter();
		String filename = "home.jsp";
		String filepath = "e:\\";
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ filename + "\"");

		// use inline if you want to view the content in browser, helpful for
		// pdf file
		// response.setHeader("Content-Disposition","inline; filename=\"" +
		// filename + "\"");
		FileInputStream fileInputStream = new FileInputStream(filepath
				+ filename);

		int i;
		while ((i = != -1) {

Step 3:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xsi:schemaLocation="" id="WebApp_ID" version="3.1">

Output Screen shot

Download file upload example
file download using servlet war
file download using servlet zip

 Related example

File upload using jsp and servlet                         

File download using jsp and servlet

Related Post


Gayathri Lekshmi
         How to make dynamic?
         For the second screenshot displayed, how do I make the screen available in such a way that, only save option is displayed as dialog. It should not contain open with.
         Hi Kiran, it depends on browser, code cannot do anything with that..
         hi, could you please check the out object,the out object is an object of printwriter class(is is not mentioned above).to download the file form server i think there should be declaration of outStream class's object and then use outStream.write(i) instead of out.write(i) . please try to help.
sunil shetty
         this program is not working in my machine.. i m getting the 404 page not found error can any one please help me
Sweta Rajbhar
         Whenever i am downloading a pdf file the contents of file are empty after file gets downloaded Why is this so ???
         May be some issue with your looping, please check again or post your code here