File Upload Example using Servlet


This article demonstrates the file upload example using JSP and Servlet. This example uses Commons FileUpload package which makes it easy to add robust, high-performance, file upload capability to your servlets and web applications. This example needs commons-fileupload-1.2.1.jar and commons-io-1.4.jar in the class path of your web application.

FileUpload parses HTTP requests, "Form-based File Upload in HTML". That is, if an HTTP request is submitted using the POST method, and with a content type of "multipart/form-data", then FileUpload can parse that request, and make the results available in a manner easily used by the caller.

uploadfile.jsp

<%@ 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>Insert title here</title>
</head>
<body>
 <form action="upload-file" method="post" name="uploadForm" enctype="multipart/form-data">
  <p>
   <input name="uploadfile" type="file" size="50">
  </p>

  <p> </p>
  <input name="submit" type="submit" value="Submit">
 </form>
</body>
</html>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
   <servlet-name>upload-file</servlet-name>
   <servlet-class>com.mycompany.mywebapp.FileUploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
   <servlet-name>upload-file</servlet-name>
   <url-pattern>/upload-file</url-pattern>
  </servlet-mapping>
</web-app>

FileUploadServlet.java

package com.mycompany.mywebapp;

import java.io.File;
import java.io.FileOutputStream;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {
 @Override
 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  // Directory where files will be saved
  File seshdir = new File("c:\\servlet");

  if (!seshdir.exists()) {
   seshdir.mkdirs();
  }

  FileItemFactory factory = new DiskFileItemFactory();

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);

  // Parse the request
  List items = null;
  try{
   items = upload.parseRequest(request);
  } catch (FileUploadException e) {
   throw new ServletException("Exception while uploading the file");
  }

  for (DiskFileItem diskFileItem : items) {
   // Exclude the form fields
   if (diskFileItem.isFormField()) {
    continue;
   }

   byte[] fileBytes = diskFileItem.get();
   File file = new File(seshdir, diskFileItem.getName());
   FileOutputStream fileOutputStream = new FileOutputStream(file);
   fileOutputStream.write(fileBytes);
   fileOutputStream.flush();
  }
 }
}

11 comments:

  1. // for (DiskFileItem diskFileItem : items)

    in Compatible type
    required: org.apache.commons.fileupload.disk.DiskFileItem
    found: java.lang.Object

    ReplyDelete
    Replies
    1. use generics.
      Declare items as
      List item;

      Delete
  2. i think it could be jar file problem

    might be it is not located properly

    ReplyDelete
  3. FileUploadServlet.java:42: incompatible types
    found : java.lang.Object
    required: org.apache.commons.fileupload.disk.DiskFileItem
    for (DiskFileItem diskFileItem : items) {
    ^
    1 error
    Compilation failed.

    ReplyDelete
  4. Looks like java 6 vs java 7 issue...

    ReplyDelete
  5. No its actually incompatible type

    ReplyDelete
  6. Try using Iterator, worked for me

    for (Iterator it = items.iterator(); it.hasNext();) {
    DiskFileItem diskFileItem = (DiskFileItem) it.next();
    if (diskFileItem.isFormField()) {
    continue;
    }
    byte[] fileBytes = diskFileItem.get();
    File file = new File(seshdir, diskFileItem.getName());
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(fileBytes);
    fileOutputStream.flush();
    }

    ReplyDelete
  7. it showing error at DiskFileItem diskFileItem : items ... in items (mismatch cant convert eleent type object to DiskFileItem

    ReplyDelete
  8. which jar file shoul be added for this programe

    ReplyDelete
  9. what should be written in the servlet to get the the file input type in servlet from jsp

    ReplyDelete
  10. Add iterator to items and cast object to DiskFileItem:

    for (Iterator it = items.iterator(); it.hasNext();) {
    DiskFileItem diskFileItem = (DiskFileItem) it.next();

    ReplyDelete