Friday, 2 October 2015

Example of downloading file from the server in servlet

Example of downloading file from the server in servlet

For downloading a file from the server, here is the simple example. I am supposing you have home.jsp file in E drive that you want to download. If there is any jar or zip file, you can direct provide a link to that file. So there is no need to write the program to download. But if there is any java file or jsp file etc, you need to create a program to download that file.

Example of downloading file from the server in servlet

In this example, we are creating three files:
  • index.html
  • DownloadServlet.java
  • web.xml

index.html
This file provides a link to download the file.
  1. <a href="servlet/DownloadServlet">download the jsp file</a>  

DownloadServlet.java
This is the servlet file that reads the content of the file and writes it into the stream to send as a response. For this purpose, we need to inform the server, so we are setting the content type as APPLICATION/OCTET-STREAM .
  1. import java.io.*;  
  2. import javax.servlet.ServletException;  
  3. import javax.servlet.http.*;  
  4.   
  5. public class DownloadServlet extends HttpServlet {  
  6.   
  7. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  8.             throws ServletException, IOException {  
  9.   
  10. response.setContentType("text/html");  
  11. PrintWriter out = response.getWriter();  
  12. String filename = "home.jsp";   
  13. String filepath = "e:\\";   
  14. response.setContentType("APPLICATION/OCTET-STREAM");   
  15. response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  16.   
  17. FileInputStream fileInputStream = new FileInputStream(filepath + filename);  
  18.             
  19. int i;   
  20. while ((i=fileInputStream.read()) != -1) {  
  21. out.write(i);   
  22. }   
  23. fileInputStream.close();   
  24. out.close();   
  25. }  
  26.   
  27. }  

web.xml file
This configuration file provides informations to the server about the servlet.
  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>DownloadServlet</servlet-name>  
  5. <servlet-class>DownloadServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>DownloadServlet</servlet-name>  
  10. <url-pattern>/servlet/DownloadServlet</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. </web-app>  

No comments:

Post a Comment