Java Servlet File Upload

This example demonstrates how to upload files with Java Servlet

Uploading a file to Java EE Servlets was always possible, but required significant effort to accomplish. Apache Foundation even built a library called Commons FileUpload to make this task easier to implement. Nevertheless Servlet 3.0 specification fixed this gap and since Java EE 6 the multipart configuration option is added to Servlets introducing the getPart and getParts methods in HttpServletRequest.

If you are interested in uploading files to the server using WebServices you can check this tutorial instead.

Servlet File Upload Example

The Servlet File upload example demonstrates the usage of MultipartConfig annotation and gives the user the ability to upload one or two files.




The structure of this example project is very simple. It consists of one servlet file FileUploadServlet.java, pom.xml to handle dependencies at build time and optional web.xml. As we already discussed in Servlet Annotation Example you may choose between annotations and a deployment descriptor to set your servlet configuration. This example uses annotations.

The picture below shows the project structure

Servlet file upload project structure

Servlet file upload project structure

In Maven’s pom.xml file the only dependency we need to declare is javax.servlet

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>net.javatutorial.tutorials</groupId>
	<artifactId>ServletFileUpload</artifactId>
	<version>1</version>
	<packaging>war</packaging>

	<name>ServletFileUpload</name>
	<url>https://javatutorial.net</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	
	<build>
		<finalName>fileuploader</finalName>
        <sourceDirectory>src/main/java</sourceDirectory>
        
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

The file upload servlet is the core of our project. It has only two methods – goGet, where we display the upload form and and doPost, which does the whole uploading job.

package net.javatutorial.tutorials;

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

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;

@WebServlet(name = "uploadServlet", urlPatterns = { "/upload" }, loadOnStartup = 1)
@MultipartConfig(fileSizeThreshold = 6291456, // 6 MB
		maxFileSize = 10485760L, // 10 MB
		maxRequestSize = 20971520L // 20 MB
)
public class FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 5619951677845873534L;
	
	private static final String UPLOAD_DIR = "uploads";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		PrintWriter writer = response.getWriter();
		writer.append("<!DOCTYPE html>\r\n")
		.append("<html>\r\n")
		.append("    <head>\r\n")
		.append("        <title>File Upload Form</title>\r\n")
		.append("    </head>\r\n")
		.append("    <body>\r\n");

		writer.append("<h1>Upload file</h1>\r\n");
		writer.append("<form method=\"POST\" action=\"upload\" ")
		.append("enctype=\"multipart/form-data\">\r\n");
		writer.append("<input type=\"file\" name=\"fileName1\"/><br/><br/>\r\n");
		writer.append("<input type=\"file\" name=\"fileName2\"/><br/><br/>\r\n");
		writer.append("<input type=\"submit\" value=\"Submit\"/>\r\n");
		writer.append("</form>\r\n");

		writer.append("    </body>\r\n").append("</html>\r\n");
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");

		// gets absolute path of the web application
		String applicationPath = request.getServletContext().getRealPath("");
		// constructs path of the directory to save uploaded file
		String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

		// creates upload folder if it does not exists
		File uploadFolder = new File(uploadFilePath);
		if (!uploadFolder.exists()) {
			uploadFolder.mkdirs();
		}

		PrintWriter writer = response.getWriter();

		// write all files in upload folder
		for (Part part : request.getParts()) {
			if (part != null && part.getSize() > 0) {
				String fileName = part.getSubmittedFileName();
				String contentType = part.getContentType();
				
				// allows only JPEG files to be uploaded
				if (!contentType.equalsIgnoreCase("image/jpeg")) {
					continue;
				}
				
				part.write(uploadFilePath + File.separator + fileName);
				
				writer.append("File successfully uploaded to " 
						+ uploadFolder.getAbsolutePath() 
						+ File.separator
						+ fileName
						+ "<br>\r\n");
			}
		}

	}

}

The @MultipatrtConfig annotations enables the servlet to accept file uploads. There are 3 important attributes:

  • fileSizeThreshold – the file size to be exceeded before file is written to temp directory. If file is smaller than this threshold the file resides in memory before requests complete.
  • maxFileSize – this is the maximum size of the file allowed to be uploaded. In the example above the user is not allowed upload a file bigger than 10 MB
  • maxRequestSize – is the maximum sum of the sizes of all files we try to upload with one request. In the example above we set this value to 20 MB which means we can upload a total of 20MB, no matter the number of files

There is a fourth attribute you may want to specify or not. It is called location and it points to which directory the web container should store temporary files. However if you do not specify this attribute the container will use the default temp folder.

We override doGet method to show a simple form with two file-chooser fields. You may want to add additional input fields as multipart attachments allow this.

The form to upload files

The form to upload files

In doPost method we first construct the path to the folder we want to store the uploaded files. Than we use request.getParts() to iterate over the files the user has selected for upload and finally store them to desired location.

Once build and deployed you can access the application in your browser at: http://localhost:8080/fileuploader/upload

You can find the project in our GitHub repository

4 1 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments