Example Of Downloading File From The Server Of Servlet


For downloading a file from the server, it is a simple example for you. We are presuming that you have a home.JSP file in E drive which you want to download. If there is any jar or zip file you can directly provide a link to that file. So, there is no need to write the whole program to download.

But if there is any java file or JSP file etc you need to make a program to download that file.

Example of downloading files from the server in servlet

We are going to create three files in this example:

  • Index.html
  • Downloadservlet.java
  • web.xml


This file provides you the link to download the file.

<a href="servlet/DownloadServlet">download the jsp file</a>


This is the servlet report that reads the content material of the report and writes it into the circulation to send as a response. For this purpose, we want to tell the server, so we're putting the content material kindly as APPLICATION/OCTET-STREAM.

import java.io.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
public class DownloadServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
PrintWriter out = response.getWriter();  
String filename = "home.jsp";   
String filepath = "e:\\";   
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
FileInputStream fileInputStream = new FileInputStream(filepath + filename);  
int i;   
while ((i=fileInputStream.read()) != -1) {  

Web.xml file

This configuration file gives information to the server about the servlet.


download this example (developed without IDE)

download this example (developed using Myeclipse IDE)

download this example (developed using Eclipse IDE)

download this example (developed using Netbeans IDE)