A simple application demonstrating how to write a Servlet code to download a Jar or file from the Server at a specified location.
1. A simple html file for sending a get request to server for the Jar/file.
2. Servlet code for downloading a Jar/file to a specified location on client's machine.
(Output) Running Download.html :
(Output) On clicking the "Download Jar" link we get the download file pop-up (Save as to specified location)
1. A simple html file for sending a get request to server for the Jar/file.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Download Jar</title> </head> <body> <h2>Download Page !!!!</h2> <a href="DownloadJarServlet">Download Jar</a> </body> </html>
2. Servlet code for downloading a Jar/file to a specified location on client's machine.
package com.download.jar; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/DownloadJarServlet") public class DownloadJar extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. Helping the browser to understand that it is // a jar file not an html content. // Inorder to pass this information in response // we set the content type as "application/jar" // by calling setContentType() method in response object response.setContentType("application/jar"); // 2. Getting the ServletContext object by calling // getServletContext() method from the current servlet object ServletContext ctx = getServletContext(); // 3. From ServletContext object we are calling getResourceAsStream() // which returns the resource located at the named path as an InputStream object. // The data in the InputStream can be of any type or length. // This method returns null if no resource exists at the specified path. // here we are passing the jar name present in the server at the relative path InputStream is = ctx.getResourceAsStream("/mail.jar"); int read = 0; byte[] noOfBytes = new byte[1024]; // 4. Getting the outputstream from the response object to write // contents of jar to browser OutputStream os = response.getOutputStream(); // 5. Reading the contents of jar in bytes using the inputstream created above // and writing it to the browser through outputstream created above. while((read = is.read(noOfBytes)) != -1 ){ os.write(noOfBytes, 0 , read); } os.flush(); os.close(); } }
(Output) Running Download.html :
(Output) On clicking the "Download Jar" link we get the download file pop-up (Save as to specified location)