Pages Navigation Menu

Coding is much easier than you think

File Upload Example in Servlet & Jsp – Java web application

 

 
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

 

JSP

 
Now create index.jsp to handle file upload as below




File Upload Example in Java web application


	

Choose File to Upload in Server

 

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




File Upload Example in Java web application

	

${requestScope["message"]}

 

Web.xml

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


   index.jsp


   UploadFile
   com.fileupload.UploadFile


   UploadFile
   /UploadFile

 

Demo

Now on Running the application
 

 
In our next article we shall learn to implement AJAX style File Upload in Java Web Application using jQuery plugin
 

3 Comments

  1. 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

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

  3. 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..