Pages Navigation Menu

Coding is much easier than you think

File Upload Example in Servlet & Jsp – Java web application

 
File upload in java
 
If you want your user to choose files from file system and upload to server then following are the important points to be noted down:

  • You need to use <input type=”file”/>.
  • Next step is that form method should be POST with enctype as multipart/form-data, which makes file data available in parts inside request body.
  • The form action attribute should be set to a servlet file which would handle file uploading at backend server. Following example is using UploadServlet servlet to upload file.

 
Recommended reading

 

Final Project Structure

 
Now create a Dynamic web project in eclipse with following project structure
File Upload in java proj
 

JSP

 
Now create index.jsp to handle file upload as below

<html>
<head>
<title>File Upload Example in Java web application</title>
</head>
<body>
	<h3>Choose File to Upload in Server</h3>
	<form action="UploadFile" method="post" enctype="multipart/form-data">
		<input type="file" name="file" /> 
		<input type="submit" value="upload" />
	</form>
</body>
</html>

 

Library

 

Servlet

 

package com.fileupload;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final String UPLOAD_DIRECTORY = "C:/Files/";

	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);

	// process only if its multipart content
	if (isMultipart) {
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
	            // Parse the request
		    List<FileItem> multiparts = upload.parseRequest(request);

                   for (FileItem item : multiparts) {
		   if (!item.isFormField()) {
   		   String name = new File(item.getName()).getName();
		   item.write(new File(UPLOAD_DIRECTORY + File.separator + name));
		   }
		}
			
		// File uploaded successfully
		request.setAttribute("message", "Your file has been uploaded!");
		} 
		catch (Exception e) 
		{
      	         request.setAttribute("message", "File Upload Failed due to " + e);
		}
	} else 
	{
	request.setAttribute("message", "This Servlet only handles file upload request");
	}
	request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}

 
Here DiskFileItemFactory is default Factory class for FileItem. It provides a method to parse the HttpServletRequest object and return list of FileItem. FileItem provides useful method to get the file name, field name in form, size and content type details of the file that is uploaded. To write file to a directory, all we need to do it create a File object and pass it as argument to FileItem write() method.
 
Do read

 

JSP

 
Create a file result.jsp to render the file upload success or error message

<html>
<head>
<title>File Upload Example in Java web application</title></head>
<body>
	<h4>${requestScope["message"]}</h4>
</body>
</html>

 

Web.xml

Servlet mapping should be done in web.xml as shown below
 

<welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
   <servlet-name>UploadFile</servlet-name>
   <servlet-class>com.fileupload.UploadFile</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>UploadFile</servlet-name>
   <url-pattern>/UploadFile</url-pattern>
</servlet-mapping>

 

Demo

Now on Running the application
 
File Upload in j2ee
 
In our next article we shall learn to implement AJAX style File Upload in Java Web Application using jQuery plugin
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

  • Harshil K. Kulkarni

    Thank for code. can you tell me how to put restriction on on file’s type like allow to only excel or pdf to upload

  • Harshil K. Kulkarni

    it’s work perfectly but how to put restriction on file types. example, only Excel or pdf allow to upload.

  • Amit Singh

    Can you please tell, how to upload file on web application over server?? where we don’t have root access.
    Which technique is will be used for secure application without using spring and struts framework..