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


         Hell0?! Th?s i? well-intentioned distant withdrawn substance but I neediness s?mе hеlp frоm аn established blog. Is it ?ard to cake up yo?r owwn blog? free sex ?'m not absolutely techincal Ьut I can pattern t?ings o?t pretty quick. I'm brainwork аbout making m? own but I'm nott s?re where to start. D? you be subjected to any apex or suggestions?