In this tutorial we are going to look at how to enable your user to upload files to your web application using Servlet/JSP. File uploading is most common feature in every web application for example uploading the profile picture, cover picture etc. We can observe these while applying government jobs and in social networking sites. I used JSP technology for front end purpose and servlet as backend both are related to java programming languages. First we will see how to create dynamic project in eclipse and creating servlet and web.xml in eclipse IDE.

Image File Uploading
Step 1: Go to File menu -> New -> Dynamic Web Project


Step 2: Sometimes web.xml will not generate while creating project so we have to create manually.



Step 3 : Create the upload.jsp file and in that take a form tag with action and encType=”multipart/
form-data” attributes. If you want to upload binary file we should encTypeattribute to form tag. Using this we can upload binary stuff and in form include two input tags one for to browse the file and another to submit (upload) the file. 

<%@ 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 Uploading using Java</title>
</head>
<body>
<form method="post" action="${ pageContext.request.contextPath}/Uploader" 
encType="multipart/form-data">
<input type="file" name="file" value="select images..."/>
<input type="submit" value="start upload"/>
</form>
</body>
</html>

Step 4: To Create servlet class in eclipse right click on src -> new -> other -> web -> servlet. Now Provide the servlet name and package name.


package Demo;

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

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

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class Uploader
 */
@WebServlet("/Uploader")
public class Uploader extends HttpServlet {
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  
  if(!ServletFileUpload.isMultipartContent(request)){
   out.println("Nothing to upload");
   return; 
  }
  FileItemFactory itemfactory = new DiskFileItemFactory(); 
  ServletFileUpload upload = new ServletFileUpload(itemfactory);
  try{
   List  items = upload.parseRequest(request);
   for(FileItem item:items){
    
    String contentType = item.getContentType();
    if(!contentType.equals("image/png")){
     out.println("only png format image files supported");
     continue;
    }
    File uploadDir = new File("F:\\UploadedFiles");
    File file = File.createTempFile("img",".png",uploadDir);
    item.write(file);

    out.println("File Saved Successfully");
   }
  }
  catch(FileUploadException e){
   
   out.println("upload fail");
  }
  catch(Exception ex){
   
   out.println("can't save");
  }
 }
}
Step 5: Finally add the tomcat server and run the code. If you face any problems please feel free to put a comment.

21 comments:

  1. Could you tell me how to upload an image file on a server on Linux. i'm having problems with the path. i know i have to use the real path but i don't really know how to use the getRealPath() method. Gracias :)

    ReplyDelete
  2. can u help, itry,but error in line 37

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. change fileitem to FileItem in tipe the list.

      Delete
    3. error is still their...
      Multiple markers at this line
      - The method parseRequest(RequestContext) in the type FileUploadBase is not applicable for the arguments
      (HttpServletRequest)
      - Fileitem cannot be resolved to a type

      Delete
  3. Hi kayum iman,

    I didn't get u, can u please paste the error here?

    ReplyDelete
    Replies
    1. I am also facing same problem in line 37.
      error is--The method ParseRequest(HttpServletRequest) is undefined for the type ServletFileUpload
      and one more thing i want to ask. instead or image i want to upload .csv file so where change will require and what.
      please help me out.

      Delete
    2. This comment has been removed by the author.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hi I had an issue when saving the image into my computer whether it's png or jpg the image can't be read always when trying to open it can u help me please I've been stuck in this for several hours

    ReplyDelete
  6. Hi sweety,
    can u paste the error message here?

    ReplyDelete
    Replies
    1. The problem is There is no error Message everything's fine but when I go the Image Location on my Computer and try to open it the Image editor return an error saying it's damaged or too large.

      Delete
    2. Which image format your uploading did u checked with both format jpg and png? Please check it once and give the exact path

      Delete
    3. To get idea please check the video demo once.

      Delete
    4. I did use jpg and png both but in vain I saw the demo
      I'm using ServletContext().getRealPath("/") as the directory where I upload the image.

      Delete
    5. Filename never is the same as source filename. it's img27536998724642373.png

      Delete
    6. I am also facing same problem in line 37.
      error is--The method ParseRequest(HttpServletRequest) is undefined for the type ServletFileUpload
      and one more thing i want to ask. instead or image i want to upload .csv file so where change will require and what.
      please help me out.

      Delete
    7. sir how can we store other image extensions like jpg

      Delete
  7. I am getting this error
    java.lang.NoSuchMethodError: org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload.parseRequest(Ljavax/servlet/http/HttpServletRequest;)Ljava/util/List;

    at line 40

    ReplyDelete
  8. i am facing this error..can anyone help me:-
    org.apache.catalina.connector.RequestFacade cannot be cast to org.apache.tomcat.util.http.fileupload.RequestContext

    ReplyDelete
  9. [-( Error in Line 37 The method ParseRequest(HttpServletRequest) is undefined for the type ServletFileUpload

    ReplyDelete

 
Top