Saturday, 7 June 2014

Servlets : Download file

🚀 Master Java Servlets & Backend Development!

Subscribe to Ram N Java for clean, beginner-friendly coding tutorials and practical web architecture guides!

👉 Click Here to Subscribe Now

How File Downloading Works in Java Servlets

Allowing users to download files (such as PDFs, images, text files, or zip archives) directly from the server is a common web application requirement. In Java Servlets, downloading a file involves setting the appropriate HTTP response headers so the client browser recognizes the response as an attachment and prompts a save dialog, followed by streaming the file bytes using ServletOutputStream.

Essential HTTP Response Headers for File Download

  • Content-Type: Identifies the MIME type of the file (e.g., application/octet-stream for arbitrary binary files or dynamic detection via ServletContext.getMimeType()).
  • Content-Disposition: Instructs the browser to download the file instead of displaying it inline. Setting attachment; filename="filename.ext" triggers the browser's download prompt.
  • Content-Length: Indicates the exact file size in bytes so the client can display an accurate download progress bar.

Step 1: Create the Download Trigger (HTML)

Provide a link or button on your webpage that directs the user to your download servlet:

<a href="DownloadServlet?fileName=sample.pdf">Download PDF File</a>

Step 2: Implement File Download in Java Servlet

In your servlet's doGet() method, locate the file on the server, set the response headers, and stream the file bytes to the client:

String fileName = request.getParameter("fileName");
ServletContext context = getServletContext();
String filePath = context.getRealPath("/downloads/" + fileName);
File downloadFile = new File(filePath);

String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
  mimeType = "application/octet-stream";
}

response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);

try (FileInputStream inStream = new FileInputStream(downloadFile);
     OutputStream outStream = response.getOutputStream()) {
  byte[] buffer = new byte[4096];
  int bytesRead = -1;
  while ((bytesRead = inStream.read(buffer)) != -1) {
    outStream.write(buffer, 0, bytesRead);
  }
}

Best Practices for Serving Downloads

  • Use Buffered Streams: Always stream binary files in chunks (buffers) rather than reading the entire file into memory at once.
  • Always Use OutputStream: Never use response.getWriter() for binary data; use response.getOutputStream() instead.
  • Validate File Paths: Prevent directory traversal attacks by validating that requested files reside strictly within permitted server directories.

📺 Related Servlets Tutorials

Learn more about request processing and stream handling from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=aofzVypK9gY

Click the below Image to Enlarge
Servlets - Download file
FileDownloadDemo Project Dir Structure
Servlets : Download file

DownloadServlet.java
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>

Environment Used 

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:

  • Servlets Tutorial
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Tutorials