How to Upload Image using JSP and Servlet

In this java web application development tutorial, We will learn to upload Images or files using JSP and Servlet. Uploading an image or profile picture is a very common requirement for any web application. Especially when you are working on any E-commerce project.

So Let’s see in detail how to upload an image using JSP and Servlet.

Upload Mutiple Images in JSP and Servlet

Browse and Upload multiple images using JSP and servlet and store them into a disk folder, below is the end-to-end example to upload images in JSP and Servlet, And perform read and write operations with images.

Maven Dependency to upload images

Below are the required dependencies to perform upload images, As in the below example, we are using the maven project so these dependencies should be in pom.xml

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.7</version>
</dependency>
JSP(index.jsp)

Define an HTML form to add the image browse and submit button. When the user selects the images or file and submit this form data will be sent to the servlet “ImageUploadCTL.java” in the form of a request.

<html>
<body>
<h2>Image Uploading example in JSP and Servlet</h2>

<form action="<%=request.getContextPath()%>/ImageUploadCTL" enctype="multipart/form-data" method="post">
  <input type="file" id="myFile" name="filename" multiple>
  <input type="submit">
</form>

</body>
</html>
Servlet(ImageUploadCTL.java)

To get the uploaded images into the servlet, Create an object of ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

and get the image list from the request by uploading objects using List<FileItem> items = upload.parseRequest(request);

Now find each images(Image name) from the list by using String fileName = fileItem.getName(); 

And Write the image using fileItem.write(new File("Path", fileName)); Replace the “Path” from the image folder location.

package com.imageupload.ctl;

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

/**
 * Servlet implementation class ImageUploadCTL
 */
@WebServlet(name = "ImageUploadCTL", urlPatterns = { "/ImageUploadCTL" })
public class ImageUploadCTL extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImageUploadCTL() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
        
        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem fileItem : items) {
                System.out.println("fileNAme: "+fileItem.getName());
                String fileName = fileItem.getName();
                fileItem.write(new File("Path", fileName));
            }
            
        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

Upload Image using JSP and Servlet (Solutions 2)

Design an Image Uploading form

Create a simple HTML form to upload an image. The below code contains A browser button to get the Image and the upload button to perform the upload operation.

<html>
<head></head>
<body>
<form action="/ImageUploading/UploadImage" method="post" enctype="multipart/form-data">
Select Image to Upload:<input type="file" name="photo">
<br>
<input type="submit" value="Upload">
</form>
</body>
</html>

Create a simple method to upload an Image

UploadImage is a custom method that takes request, Response, and name of the file as arguments.

public static String UploadImage(HttpServletRequest request, HttpServletResponse response,String name)
    throws ServletException, IOException {
  String savePath = "F:\\Java Tutorial\\ImageUploading\\src\\main\\webapp\\img";
  File fileSaveDir = new File(savePath);
  if (!fileSaveDir.exists()) {
    fileSaveDir.mkdir();
  }
  Part part = request.getPart("photo");
  String fileName = extractFileName(part);
  part.write(savePath + File.separator + name+fileName);
  return name+fileName;

}

Create Servlet(UploadImage.java)

package com.Image.Uploading;

import java.io.IOException;
import java.nio.file.Paths;

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

/**
 * Servlet implementation class UploadImage
 */
@WebServlet(name = "UploadImage", urlPatterns = {"/UploadImage"})
@MultipartConfig(maxFileSize = 169999999)
public class UploadImage extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadImage() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    response.getWriter().append("Served at: ").append(request.getContextPath());
    
    
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doGet(request, response);
    Part part = null;
    try {
      part = request.getPart("photo");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ServletException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    String fileName = Paths.get(part.getSubmittedFileName()).getFileName().toString();

    Utitlity.subImage(request, response, fileName);
  }

}

OUTPUT

Image Uploading in JSP and Servlet
Image Uploading in JSP and Servlet