Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver. In this article, we will learn to download a file such as .docx, .pdf, .png etc,. from the server using Servlets.
Step by Step Implementation
Create an HTML page for the user interaction. Create Java Servlet to handle the client request, process, and send the response to the client browser.
index.html
HTML
<!DOCTYPE html> < html > < head > < meta charset = "ISO-8859-1" > < title >Welcome</ title > </ head > < body > < form action = "download" method = "get" > < h2 >Welcome to Lazyroar.</ h2 > < h3 >Download the updated Data structures course structure here.</ h3 > < input type = "submit" value = "Download" /> </ form > </ body > </ html > |
In index.html, we are making a user interaction with the input form. Once the user clicks the download button, based on the form action and method attributes, the servlet container will map the doget() method in the respective servlet.
Download.java
Java
import java.io.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; @WebServlet ( "/download" ) public class Download extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get PrintWriter object PrintWriter out = response.getWriter(); // File name String pdfName = "DataStructures.docx" ; // File path String pdfPath = "e:\\" ; // Set the content type and header of the response. response.setContentType( "application/msword" ); response.setHeader( "Content-Disposition" , "attachment; filename=\"" + pdfName + "\"" ); // Get FileInputStream object to identify the path FileInputStream inputStream = new FileInputStream(pdfPath + pdfName); // Loop through the document and write into the // output. int in; while ((in = inputStream.read()) != - 1 ) { out.write(in); } // Close FileInputStream and PrintWriter object inputStream.close(); out.close(); } } |
We are using @WebServlet() annotation to map the request URL to the respective servlet instead of using deployment descriptor – web.xml. As we specified the method to get in the client request, the container will execute doget() method in Download.java servlet. We need to provide the file name which has to be downloaded through the browser and its location. In this example, we are using .docx file. We need to specify the content type of the response as “application/msword“, so that it describes what type of content is being sent through the response.
Java
response.setContentType( "application/msword" ); |
Content-Type:
The Content-Type header describes the content of the body part.
Format:
Content-type: type/subtype; parameter=value; parameter=value…
- type – It describes the type of content of the body part like Text, Multipart, Message, Application, Image, Audio, and Video.
- subtype – It further describes the content type like text/plain, application/octet-stream, and image/jpeg.
- parameter – It is specific to Content-type/subtype pairs and values.
Based on the request and response, it is important to set the response content type that is used in the application. In general, while downloading the files using Servlet, the application/octet-stream content type is used. It is described for unknown binary files. Usually, it is an application or a document opened in an application such as a spreadsheet/pdf/word processor. This preserves the file contents, but the receiver has to determine the file type from the filename extension. But, if we know the specifics of the file, we can set the content type of the response with the below different formats.
For the files like Text, PDF, Document, Excel:
- application/octet-stream
- application/pdf
- application/msword
- application/zip
- text/csv
For the files like Images, Videos:
- image/jpeg
- image/png
- image/bmp
- image/gif
- video/mp4 etc.
Now, we need to set the response header which provides the detailed context of the response.
Content-disposition:
Content-disposition provides the presentation information for the response body-part. While working with attachments, this header can be used to specify whether the attachment body part should be displayed (inline) or presented as a file name to be copied (attachment).
Format:
Content-disposition: disposition_type; parameter=value;parameter=value…
- disposition_type – To specify whether inline (display the body part) or attachment (present as file to save.)
Attachment usually has the parameter filename with a value specifying the suggested name for the saved file. In this example, we are specifying disposition_type as attachment and its parameter value that is the file name and its path.
Java
response.setHeader( "Content-Disposition" , "attachment; filename=\"" + pdfName + "\"" ); |
Once the servlet accesses the file, now we need to read the contents of the file using FileInputStream. So, get the object of the FileInputStream and loop through the document to read and write to the PrintWriter object. Finally close the connections – FileInputStream and PrintWriter objects.
Output:
Run the index.html file. URL: http://localhost:8081/DownloadServlet/index.html
Once we click Download, the document will be downloaded in the browser like below.
This way, we can download any type of file like text file, image file, or video file using Servlets by specifying the respective the content-type and headers in the response.