How Upload Image using JSP and Servlet

In this java web application development tutorial, We will learn to upload Images using JSP and Servlet. Uploading 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 see in detail how to upload an image using JSP and Servlet.

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);
  }

}