File Upload in Java Servlet Example

File upload is a common functionality which is used in most of the web application. Initially, people depend on third-party library Apache’s common-fileupload and common-io to implement file upload operation. In this article, we will use the built-in library from Servlet3.0 API to develop the file uploading example in java. Here we will be able to upload a single file as well as multiple file upload at a time.

Servlet3.0 API For File Upload

Let’s have a look to annotation, class and method which is used in this article to implement file upload.

@MultipartConfig Annotation

The MultipartConfig annotation is responsible for handle the multipart/form-data requests as in file upload definitely requests should be in multipart/form-data. This annotation is used on top of the Servlet. Followings are the possible options to configure:

  • fileSizeThreshold: size(in bytes) of the file that is greater than this threshold will be directly written to disk, instead of saving in memory.
  • location: directory location where the file will be stored by method Part.write().
  • maxFileSize: maximum allowed size(in bytes) for a single file.
  • maxRequestSize: maximum allowed size(in bytes) for a request.

The Part Interface

The class of this interface represents a part as uploaded to the server as part of a multipart/form-data request body. The part may represent either an uploaded file or form data. The Part retrieve multipart/form-data request by a Servlet annotated with MultipartConfig by calling getPart(java.lang.String) or getParts() of HttpServletRequest.

Sample Java File Upload Example

We are going to create a eclipse maven application. In this application the following files are required to create:

  • FileUploadServlet.java
  • fileupload.html
  • success.html
  • error.html
  • pom.xml

Eclipse Project Structure

FileUploadServlet.java

package com.javacodepoint.fileupload;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
 * 
 * @author javacodepoint
 *
 */
@WebServlet("/UploadServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
		maxFileSize = 1024 * 1024 * 5, // 5MB
		maxRequestSize = 1024 * 1024 * 100) // 100MB
public class FileUploadServlet extends HttpServlet {
	
	/**
     * Location to save uploaded files on server
     */
	private static final String UPLOAD_PATH = "D:/uploads";
	
	/**
     * Method to get file name from HTTP header content-disposition
     */
	private String getFileName(Part part) {
		String contentDisp = part.getHeader("content-disposition");
		String[] items = contentDisp.split(";");
		for (String s : items) {
			if (s.trim().startsWith("filename")) {
				return s.substring(s.indexOf("=") + 2, s.length() - 1);
			}
		}
		return null;
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String resultPage="/success.html";
		try {
			File uploadsPath = new File(UPLOAD_PATH);
			if (!uploadsPath.exists()) {
				//create upload folder if not exist.
				uploadsPath.mkdir();
			}
			for (Part part : request.getParts()) {
				String fileName = getFileName(part);
				if(fileName!=null) {
					part.write(UPLOAD_PATH + File.separator + fileName);
				}
			}
			System.out.println("File uploaded successfully!");
		} catch (Exception e) {
			System.err.println("Error while uploading files!");
			e.printStackTrace();
			resultPage="/error.html";
		}
		getServletContext().getRequestDispatcher(resultPage).forward(request, response);
	}
}

fileupload.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload</title>
</head>
<body>
<center>
    <h1>File Upload</h1>
    <form method="post" action="UploadServlet"
        enctype="multipart/form-data">
        Select file to upload: <input type="file" name="file" size="60" multiple="true" /><br />
        <br /> <input type="submit" value="Upload" />
    </form>
</center>
</body>
</html>

success.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Success | File Upload</title>
</head>
<body>
<center>
    <h1 style="color:green">File Upload Successfully!</h1>
    <a href="./fileupload.html">Upload again</a>
</center>
</body>
</html>

error.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Error | File Upload</title>
</head>
<body>
<center>
    <h1 style="color:red">Something went wrong!</h1>
    <p>Please check your configurations</p>
    <a href="./fileupload.html">Try again</a>
</center>
</body>
</html>

pom.xml

<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.javacodepoint</groupId>
	<artifactId>JavaFileUpload</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.0.1</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

Conclusion

With the built-in API of Servlet3.0, without depending on any third-party library we will be able to do a single as well as Multiple file upload in java. Now it is very easy to use @MultipartConfig, Part Interface methods, and some newly added methods of HttpServletRequest to implement file upload operation in java.

Download Complete Eclipse Project Here

Leave a Comment

Your email address will not be published. Required fields are marked *