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


Now create index.jsp to handle file upload as below

<title>File Upload Example in Java web application</title>
	<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" />






package com.fileupload;

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



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

<title>File Upload Example in Java web application</title></head>



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




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

I'm a Full stack developer of IT exp in J2EE, AngularJs, MicroServices, Docker, Spring (Boot, MVC, Cloud), Bluemix, DevOps. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

%d bloggers like this: