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.
- <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 .
- 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 provides informations 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>
No comments:
Post a Comment