File upload using Servlet 3.0 API in JAVA

 

In this post I will explain the file uploading procedure using JAVA’s own Servlet API. Before java 1.7 there was no support for file uploading, hence we were using various 3rd part APIs(like Apache Commons, Orilley, etc.).

Required Resources:
Servlet 3.0 API and a web/application server supporting JAVA EE 7 and above. Here I am using Tomcat 7.

Folder Structure:
File Uploader Using Servlet API Folder Structure

Files:

1) Web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FileUploadUsingServlet</display-name>
  <welcome-file-list>
    <welcome-file>home.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2) home.jsp :
This is the home page of the application. In this file we have a form having a file type input field. For file uploading the ‘enctype’ attribute of the <form> tag should be ‘multipart/form-data’.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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 using servlet</title>
	</head>
	<body>
		<center>
			<form action="uploadServlet" method="post" enctype="multipart/form-data">
				Select file to upload : <input type="file" name="fileName"/></br></br>
				<input type="submit" value="Upload" />
			</form>
			<h5>${message}</h5>
		</center>
	</body>
</html>

3) UploaderServlet.java:
Here we have annotated the Servlet class with @WebServlet annotation. This annotation is used to declare the servlet and the servlet class must extends ‘HttpServlet’ class. The argument provided here is the URL pattern, so we don’t need to define separately this servlet in web.xml file.

The servlet is also annotated with @MultipartConfig to handle the ‘multipart/form-data’ request. This annotation has following properties:

a) maxFileSize : maximum allowed size of a file to upload whose value is provided in Bytes. The default value of this attribute is -1L (which means unlimited).

b) fileSizeThreshold: the maximum file size beyond which the file will be directly written to the disk. It also takes value as bytes.

c) maxRequestSize: Maximum allowed size of multipart/form-data request. It also takes value in bytes and the default value is -1L (unlimited).
Part is the interface which represents a part of the form data that was received within a ‘multipart/form-data’ POST request. Here we are using its write method to save the file into the directory.

We can get the content disposition by calling the ‘getHeaders(“content-disposition”)’ method of Part interface. It returns a String from which we can get the file name. We can see the code to extract the file name below.

package com.uploader;

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;

@WebServlet("/uploadServlet")
@MultipartConfig(fileSizeThreshold = 1024*1024*2,maxFileSize = 1024*1024*10,maxRequestSize = 1024*1024*50)
public class UploaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Override
	public void init()throws ServletException{
		System.out.println("servlet initialized");
	}
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pathToUpload = "D:\\upload";
		
		//creating the save directory if it doesn't exist
		File uploadDirectory = new File(pathToUpload);
		if(!uploadDirectory.exists()){
			uploadDirectory.mkdirs();
		}
		
		//Iterating the parts received from 'multipart/form-data' request
		for(Part part : request.getParts()){
			//extracting the file name
			String fileName = null;
			String contentDisposition = part.getHeader("content-disposition");
			String[] strgs = contentDisposition.split(";");
			for(String strng : strgs) {
				if(strng.trim().startsWith("filename")){
					fileName = strng.substring(strng.indexOf("=")+2, strng.length()-1);
				}
			}
			pathToUpload = pathToUpload+File.separator+fileName;
			part.write(pathToUpload);
			request.setAttribute("message", pathToUpload);
			getServletContext().getRequestDispatcher("/home.jsp").forward(request, response);
		}
	}

}

COMMENTS ( 2 )

Its including you read my mind! You appear to comprehend a whole
lot about this, like you wrote the e book within it or something.

I feel which you can use some % to pressure your message house a little bit, but other than that, this is wonderful blog.
A wonderful read. I am going to definitely be back.

Reply

Your look is unique as compared to other folks I’ve read stuff from.
I appreciate you for posting when you’ve got the means, Guess
I’ll just book mark this page.

Reply

Leave a comment

SUBSCRIBE TO NEWSLETTER

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories