Java file upload by example with Servlets & JSPs

While social media websites such Facebook and LinkedIn made it incredibly easy for a user to upload image files, the back-end implementation of such a feature has been anything but easy. Prior to the Java EE 7 release, developers struggled to implement a Servlet file upload component because it was a rather sordid affair that required a great deal of error-prone and bloated code.

Fortunately, the Servlet 3.1 release changed all that for developers with Java file upload concerns.

Java file uploads

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

  1. Create a basic HTML or JSP file that contains an HTML5 file input form element;
  2. From the form, invoke a Java Servlet to handle the server-side processing of the file;
  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 uploaded file to the server’s file system; and
  6. Send a response back to the browser to indicate that the file successfully uploaded.

HTML5 file input tags

The HTML5 file input type tag makes it possible to render a file selector in any modern browser. A programmer should include the input tag within an HTML5 form tag whose action attribute points to a file upload Servlet and set the enclosing form’s enctype attribute to be multipart/form-data. Then, the developer should 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 to the webapps folder of your Java web module.

<!DOCTYPE html> 
<html> 
<head> 
<title> Java File Upload Servlet Example </title> 
</head> 
<body>

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

</body>
</html>

The file upload Servlet

The Java file upload Servlet will contain a doPost method to handle the form submission. In this doPost method, the uploaded file will process in parts. After the file uploads, the Java Servlet saves each part to a like-named file in the C:\upload\ folder on the server’s file system.

More File Upload Options

I put together a bunch of file upload tutorials. Pick your technology and get uploading!

Uploading files to the server need not be a problem.

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

The complete 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 Java Servlet file upload example

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

When the application runs, a file selector will appear in the user’s browser. The user can then select a file from their computer and click the “Upload” button to submit the file to the server. The Java file upload Servlet will then capture that file and persist it to the C:\uploads folder on the server.

PHP file upload example

An Ajax and Java file upload component allows for asynchronous file uploads from the browser.

Java and Ajax file uploads

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

<!DOCTYPE html> 
<html> 
<head> 
<title> Java Ajax File Upload Example </title> 
</head> 
<body>
  <!-- HTML5 Input Form Elements -->
  <input id="ajaxfile" type="file"/> <br/>
  <button onclick="uploadFile()"> Upload </button>

  <!-- Ajax to Java File Upload Logic -->
  <script>
  async function uploadFile() {
    let formData = new FormData(); 
    formData.append("file", ajaxfile.files[0]);
    await fetch('fileuploadservlet', {
      method: "POST", 
      body: formData
    }); 
    alert('The file upload with Ajax and Java was a success!');
  }
  </script>
</body> 
</html>

File uploads with Java

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

The following Maven POM file was used to build the Java Servlet file upload example:

<project xmlns="http://maven.apache.org/POM/4.0.0"
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">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.mcnz</groupId>
 <artifactId>java-file-upload-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>

 <dependencies>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
  </dependency>

 </dependencies>

 <build>
  <plugins>
   <plugin>
    <artifactId>maven-resources-plugin</artifactId>
    <version>3.2.0</version>
   </plugin>

   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.3.1</version>
    <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>

  <plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.8.0</version>
   <configuration>
    <source>1.8</source>
    <target>1.8</target>
   </configuration>
  </plugin>

  </plugins>
 </build>
</project>

App Architecture
Software Quality
Cloud Computing
Security
SearchAWS
Close