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, 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="" xmlns:xsi=""





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

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		PrintWriter writer = response.getWriter();
		writer.append("<!DOCTYPE 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\" ")
		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("    </body>\r\n").append("</html>\r\n");

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


		// 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()) {

		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")) {
				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

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Digg thisPin on PinterestShare on RedditShare on StumbleUponPrint this pageEmail this to someone

Leave a Reply

Be the First to Comment!