Servlet 3 file upload example

In this post, you will learn:

  • How to upload a file using a servlet 3 API?
  • How to use @MultiPart annotation?
  • How to use Part interface?

Steps required to upload a file:

1. In html form, request type is set to post and enctype is set to multipart/form-data.

2. <input type=”file” > element is used in the html form to facilitate selection of the file from the file system.

3. In the servlet multi part request is parsed to obtain file and other form field information.

4. File contents are saved on the server.

How to process a multi part request in a servlet?

Before Servlet 3 API, there was no direct support for processing multi part requests in a servlet. Third party APIs were required for uploading file. In Servlet 3 API, @MultipartConfig annotation and Part interface are provided to process multi part requests.

@MultipartConfig annotation:

This annotation is used to annotate those servlets which process multi part requests. It supports following parameters:

1. maxFileSize: It is used to specify the max size of the file to be uploaded.

2. fileSizeThreshold: It is used to specify the size limit above which files are directly saved to the disk. Such file contents are not stored in the memory on the server.

3. location: It is used to specify the location on the server where uploaded files are to be saved.

Processing individual parts of a multi part request using servlet 3 API:

To facilitate processing of individual parts of a multi part request, Part interface is provided by Servlet 3 API. For each part an object of type Part is created. To obtain these part objects following additional methods are added to the HttpServletRequest interface:

1. getParts() This method is used to obtain a collection of all the Part objects.

public Collection<Part> getParts();

2. getPart() This method is used to obtain a specific Part object.

public Part getPart(String partName);

Commonly used methods of the Part interface are:

1. getHeader() This method is used to obtain the header of a part as a String.

public String getHeader(String headerName);

2. getSize() This method is used to obtain the Size of the uploaded file.

public long getSize();

3. getInputStream() This method is used to obtain an input stream for reading the part contents.

public InputStream getInputStream();

4. write() This method is used to save the file contents to the disk.

public void write(String path);

Servlet 3 file upload example:

To demonstrate the servlet 3 file upload capabilities, I have modified apache file upload example using @MultipartConfig annotation and Part interface. Here is the modified code:

First, the index.html :

<form method="post" action="uploaderServlet" enctype="multipart/form-data">
Name: <input type="text" name="name"><br/>
Profile Image:<input type="file" name="toBeUploaded"><br/>
<input type="submit" value="Submit">			   
</form>

Second the UploaderServlet. It is annotated by @WebServlet & @MultipartConfig annotations. In the doPost, two Part objects are obtained to process text and file form fields.

package com.techmentro.learningpad;

import java.io.*;

import java.util.Scanner;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(urlPatterns={"/uploaderServlet"})
@MultipartConfig(maxFileSize=1024*1024*10,location)//10MB max file size is set.
public class UploaderServlet extends HttpServlet
{
	
	public void doPost(
			HttpServletRequest request, 
			HttpServletResponse response)
			 {
		PrintWriter out=null;
		
		try
		{
			
		out=response.getWriter();
		response.setContentType("text/html");
		
			
		//obtain the path of the upload folder
		String path=getServletConfig().getServletContext().getRealPath("WEB-INF/classes/uploads");
		
		//name parameter part is obtained from the request.
		Part paramPart=request.getPart("name");
		
		//To obtain the userName from the Part object, an input stream is obtained.
		Scanner in=new Scanner(paramPart.getInputStream());
		//Value of the parameter is obtained.
		String name=in.nextLine();
		//input stream is closed.
		in.close();
		
		// File part is obtained.
		Part filePart=request.getPart("toBeUploaded");
		//To obtain the file name Content-Disposition header is obtained from the part
		//FileName is part of this header. It has following format: Content-Disposition: form-data; name="nameofFileTextField"; filename="...."
		String header=filePart.getHeader("Content-Disposition");
		//fileName is obtained from the header.
		String fname=header.substring(header.lastIndexOf("=")+1);
		//Quotes around the fileName are removed.
		fname=fname.replace("\"","");
		   	//Path to save the file is generated 
                String filePath=path+File.separator+fname;
                //uploaded contents are saved to the file.
                filePart.write(filePath);
                out.write(name+ ", your profile image of size "+getSizeString(filePart.getSize())+" is uploaded successfully.");
        
		
		
		}catch(Exception ex)
		{
			out.println(ex);
		}
	}
	
	
public String getSizeString(float sizeInBytes)
{
	if(sizeInBytes<1024)
		return sizeInBytes+" Bytes";
	else if(sizeInBytes <1024*1024)
	{
		return sizeInBytes/1024+" KB";
	}
	else
	{
		return sizeInBytes/1024*1024+" MB";
	}
}
}

There is no web.xml file as the servlet configuration is provided using annotation.

With the help of Part interface & @MultipartConfig annotation, file uploaded is simplified as can be seen by this example.


Example Source Code

If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

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