logo

Example Of Downloading File From The Server Of Servlet


Show

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

Index.html

This file provides you the link to download the file.

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

DownloadServlet.java

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 {  
  
response.setContentType("text/html");  
PrintWriter out = response.getWriter();  
String filename = "home.jsp";   
String filepath = "e:\\";   
response.setContentType("APPLICATION/OCTET-STREAM");   
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  
FileInputStream fileInputStream = new FileInputStream(filepath + filename);  
            
int i;   
while ((i=fileInputStream.read()) != -1) {  
out.write(i);   
}   
fileInputStream.close();   
out.close();   
}  
  
}  

Web.xml file

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

<web-app>  
  
<servlet>  
<servlet-name>DownloadServlet</servlet-name>  
<servlet-class>DownloadServlet</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>DownloadServlet</servlet-name>  
<url-pattern>/servlet/DownloadServlet</url-pattern>  
</servlet-mapping>  
  
</web-app>

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)