Click here to watch in Youtube : https://www.youtube.com/watch?v=aofzVypK9gY
Click the below Image to Enlarge
Servlets - Download file |
Servlets : Download file |
import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; 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; public void init() throws ServletException { System.out.println("-----------------------------------------"); System.out.println(" Init method is called in " + this.getClass().getName()); System.out.println("--------------------------------------"); } public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String filename = "RamTest.docx"; String filepath = "D:\\Tomcat\\"; 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(); } public void destroy() { System.out.println("-----------------------------------------"); System.out.println(" destroy method is called in " + this.getClass().getName()); System.out.println("-----------------------------------------"); } }
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true" version="3.0"> <display-name>FileDownloadDemo</display-name> <description> This is a simple web application with a source code organization based on the recommendations of the Application Developer's Guide. </description> <servlet> <servlet-name>DownloadServlet</servlet-name> <servlet-class>DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/downloadfile</url-pattern> </servlet-mapping> </web-app>
index.html
<html> <body> <a href="downloadfile">Download file</a> </body> </html>
JDK version :1.7.0_51
Tomcat version : 7.0.50
To Download FileDownloadDemoApp Project Click the below link
https://sites.google.com/site/javaee4321/servlets/FileDownloadDemoApp.zip?attredirects=0&d=1
See also:
No comments:
Post a Comment