Servlet - Downloading File

Last Updated : 16 May, 2026

Servlets provide a way to build server-side Java applications that can handle HTTP requests and generate dynamic responses. File downloading in Servlets allows users to download files stored on the server directly through a browser. In this process, the server reads the file and sends it to the client using response streams. 

  • Used to download files like images, PDFs, ZIP, and documents
  • Uses HttpServletResponse to write file data to output stream
  • Sets response headers to control file download behavior

How File Download Works in Servlet

When a user requests a file, the servlet reads the file from the server directory and writes its content to the response output stream. The browser then downloads the file instead of displaying it.

  • The servlet sets response headers like Content-Disposition to force the browser to download the file.
  • The file is transferred as a byte stream using InputStream and OutputStream for efficient data handling.

Important Methods Used

MethodDescription
getParameter()Gets file name from request
FileInputStreamReads file from server
getOutputStream()Sends file to browser
setHeader()Sets download file name

Step by Step Implementation to Download File

This example demonstrates how a file (like .docx, .pdf, .png) can be downloaded from the server using a Servlet. The servlet reads the file from the server directory and sends it to the browser using response streams.

Step 1: Create Dynamic Web Project

  • Open Eclipse IDE
  • Create a project: ServletFilterchain
  • Select: Dynamic Web Project
  • Click Finish

Step 2: Create HTML Page (index.html)

This form triggers a GET request to the servlet mapped at /download when the user clicks the Download button. The request is sent directly to the server without any input data. The servlet then processes the request and initiates the file download response.

HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
    <form action="download" method="get">
        <h2>Welcome to GeeksforGeeks.</h2>
        <h3>Download the updated Data structures course structure here.</h3>
        <input type="submit" value="Download" />
    </form>
</body>
</html>

 Step 3: Create Download Servlet

This servlet handles a GET request at /download and reads a file from the server using FileInputStream, then writes it to the response output stream so the browser downloads it as an attachment.

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();
    }
}

Step 4: web.xml (Optional if not using annotation)

The web.xml file is used to manually configure and map the servlet with a specific URL pattern. It acts as a deployment descriptor that tells the server which servlet should be executed when a particular request URL is accessed.

XML
<web-app>

    <servlet>
        <servlet-name>Download</servlet-name>
        <servlet-class>Download</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Download</servlet-name>
        <url-pattern>/download</url-pattern>
    </servlet-mapping>

</web-app>

Step 5: Run the Application

  • Start Apache Tomcat Server
  • Deploy the project in IDE (Eclipse/IntelliJ)
  • Run the application
  • Open browser and hit:

http://localhost:8081/DownloadServlet/index.html

Output:
your browser will open with:

Output
index.html page

Once we click Download, the document will be downloaded in the browser like below.


 

Output
Downloading the document

Explanation: This servlet handles a file download request by reading a file from the server directory using FileInputStream. It sets proper response headers like Content-Type and Content-Disposition to force the browser to download the file instead of displaying it. The file content is then written to the response output stream and sent to the client for download.

Comment