Simple Java File Downloads with Servlets, JSPs, and Samples

While social media websites like Facebook and LinkedIn have made it incredibly easy for a user to upload image files, implementing such a feature in the background has been anything but easy. Prior to Java EE 7, developers struggled to implement a Servlet file upload component as it was a pretty sleazy business that required a lot of error-prone and bulky code.

Fortunately, version 3.1 of Servlet changed all that for developers having problems downloading Java files.

Java File Downloaders

You will need to perform the following steps to create a Java Servlet file upload component:

  1. Create a basic HTML or JSP file containing an HTML5 file input form element;
  2. From the form, call a Java servlet to handle the processing of the file on the server side;
  3. Code a Java servlet to handle the file upload process;
  4. Annotate the file upload servlet with the @MultipartConfig annotation;
  5. In the servlet, save the downloaded file to the server file system; and
  6. Return a response to the browser to indicate that the file was downloaded successfully.

HTML5 file input tags

The HTML5 file entry type tag can display a file picker in any modern browser. A programmer should include the input tag in an HTML5 form tag whose action attribute points to a file upload servlet and set the enclosing form’s enctype attribute to multipart / form-data. Then the developer needs to add a submit button and the HTML component required to upload a file from a browser to a Java servlet is complete.

Save the following code in a file named input.html and save it in the webapps folder of your Java web module.

 
 
 
 Java File Upload Servlet Example  
 


  
method="post" action="fileuploadservlet" enctype="multipart/form-data"> type="file" name="file" /> type="submit" value="Upload" />

The file download servlet

The Java File Upload servlet will contain a doPost method to handle form submission. In this doPost method, the uploaded file will be processed in several parts. After the file is uploaded, the Java servlet saves each part in a file of the same name in the C: upload folder on the server file system.

Website performance tips and tricks

Here’s how to improve your website’s performance:

Follow these steps and you will have a super fast website in no time!

The servlet provides multipart processing capabilities by adding the @MultipartConfig annotation to the start of the class. This annotation also allows the developer to set various file upload properties, such as maxFileSize, maxRequestSize, and fileSizeThreshold.

The full code for the file upload servlet looks like this:

package com.mcnz.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig(
  fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
  maxFileSize = 1024 * 1024 * 10,      // 10 MB
  maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class FileUploadServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    /* Receive file uploaded to the Servlet from the HTML5 form */
    Part filePart = request.getPart("file");
    String fileName = filePart.getSubmittedFileName();
    for (Part part : request.getParts()) {
      part.write("C:upload" + fileName);
    }
    response.getWriter().print("The file uploaded sucessfully.");
  }

}

Run the sample Java Servlet file download

With the Java Servlet code, the application can be deployed to any Java application server that supports the Servlet specification 3.1 or later. In this example Java file download, the target server is Tomcat 9, although the latest JBoss, Jetty, WebSphere, or OpenLiberty servers will also work.

When the application runs, a file picker appears in the user’s browser. The user can then select a file on their computer and click on the “Upload” button to submit the file to the server. The Java File Upload servlet will then capture this file and store it in the C: uploads folder on the server.

An Ajax and Java file download component enables asynchronous file downloads from the browser.

Java and Ajax file downloads

If you want to get fancy and do an asynchronous file upload with Java, add the Ajax functionality by editing the HTML file. If you replace the markup in the HTML file with what is below, the request-response cycle will be asynchronous and the user will never have to leave the original page.

 
 
 
 Java Ajax File Upload Example  
 

  
  id="ajaxfile" type="file"/> 

File downloads with Java

The Servlet API 3.1 and the HTML5 specification has made it incredibly easy to add Java and Servlet file download functionality to modern web applications. If a user needs to upload images and documents to be managed on the server, it is quick and easy for a developer to solve the problem with a Java based web offering.

The following Maven POM file was used to create the sample Java Servlet file download:


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
 4.0.0
 com.mcnz
 java-file-upload-example
 0.0.1-SNAPSHOT
 war

 
  
   javax.servlet
   javax.servlet-api
   4.0.1
  

 

 
  
   
    maven-resources-plugin
    3.2.0
   

   
    org.apache.maven.plugins
    maven-war-plugin
    3.3.1
    
      false
    
   

  
   org.apache.maven.plugins
   maven-compiler-plugin
   3.8.0
   
    1.8
    1.8
   
  

  
 

Comments are closed.