News Stay informed about the latest enterprise technology news and product updates.

Simple Java file uploads with Servlets, JSPs and examples

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 uploaders

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> 
<title> Java File Upload Servlet Example </title> 

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


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.

Website Performance Tips and Tricks

Here’s how to improve how your website performs:

Follow these steps and you’ll have a lightning fast website in no time!

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 javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
  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> 
<title> Java Ajax File Upload Example </title> 
  <!-- HTML5 Input Form Elements -->
  <input id="ajaxfile" type="file"/> <br/>
  <button onclick="uploadFile()"> Upload </button>

  <!-- Ajax to Java File Upload Logic -->
  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!');

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=""