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

Simple file uploads with Java Servlets and JSPs example

While social media sites like Facebook and LinkedIn have made the requirement to easily upload images files with a basic user expectation, the back-end implementation of such a feature has never been particularly easy. In fact, even prior to the Java EE 7 release, the implementation of a Servlet file upload component was a rather sordid affair that required a great deal of error-prone and bloated code. Fortunately, the Servlet 3.1 release changed all of that.

Java file uploaders

You will need to perform the following steps in order to create Java Servlet file upload component include:

  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
  6. Send a response back to the browser indicating the file was uploaded successfully

HTML5 file input tags

The HTML5 file input type tag makes it possible to render a file selector in any modern browser. Include this 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. 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 is processed in parts. When the file has finished uploaded, 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 multipart processing capabilities of the Servlet are provided 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 example is as follows:

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 tutorial the target server is Tomcat 9, although the latest JBoss, Jetty, WebSphere or OpenLiberty servers will suffice as well.

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, Ajax functionality can be added simply by editing the HTML file. If you replace the markup in HTML file with what is 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 requirement exists to upload images and documents for the server to manage, a Java based web solution can be quickly and easily implemented.

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>

 

 

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

SearchAppArchitecture

SearchSoftwareQuality

SearchCloudComputing

SearchSecurity

SearchAWS

Close