Upload Image using Servlet

In this example program a form is displayed to user, where user can browse the image file which is to be uploaded on the server.

Upload Image using Servlet

Upload Image using Servlet

     

This application illustrates how to upload an image using servlet.

In this example program a form is displayed to user, where user can browse the image file which is to be uploaded on the server. Once the submit button is clicked the form data is posted to a servlet. Servlet then processes the uploaded data and saves the image on the server.

Following programming code is developed in the application:

  1. Form JSP:
    Form JSP file is used to display the form to the user.
  2. Servlet (UploadImage.java):
    The UploadImage servlet is used to process the form data. After processing the form data, image is saved in the images directory of the server. Servlet also saves the path of the image into database. Finally the uploaded image is displayed on the browser with success message.

 

The Complete Application is as follows:

Uploaded image shows on the browser:

 

Source Code of uploadImage.jsp 

<html>

<head><title>Image Upload</title></head>

<body>
  <form action="/example/UploadImage" method="post" 
  
enctype="multipart/form-data" 
   name=
"productForm" id="productForm"><br><br>
  <table width="400px" align="center" border=
  style=
"background-color:ffeeff;">
  <tr>
  <td align="center" colspan=style="
   font-weight:bold;font-size:20pt;"
>
   Image Details</td>

  </tr>

  <tr>
  <td align="center" colspan=2>&nbsp;</td>
  </tr>

  <tr>
  <td>Image Link: </td>
  <td>
  <input type="file" name="file" id="file">
  <td>
  </tr>

  <tr>
  <td></td>
  <td><input type="submit" name="Submit" value="Submit"></td>
  </tr>
  <tr>
  <td colspan="2">&nbsp;</td>
  </tr>

  </table>
  </form>
</body>

</html>

 

Source Code of UploadImage.java

import java.io.*;
import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class UploadImage extends HttpServlet{
  public void doPost(HttpServletRequest request, 
  HttpServletResponse response

 
throws ServletException, IOException {
  PrintWriter out = response.getWriter();
  boolean isMultipart = ServletFileUpload.isMultipartContent(
  request
);
  System.out.println("request: "+request);
  if (!isMultipart) {
  System.out.println("File Not Uploaded");
  else {
  FileItemFactory factory = new DiskFileItemFactory();
  ServletFileUpload upload = new ServletFileUpload(factory);
  List items = null;

  try {
  items = upload.parseRequest(request);
  System.out.println("items: "+items);
  catch (FileUploadException e) {
  e.printStackTrace();
  }
  Iterator itr = items.iterator();
  while (itr.hasNext()) {
  FileItem item = (FileItemitr.next();
  if (item.isFormField()){
  String name = item.getFieldName();
  System.out.println("name: "+name);
  String value = item.getString();
  System.out.println("value: "+value);
  else {
  try {
  String itemName = item.getName();
  Random generator = new Random();
  int r = Math.abs(generator.nextInt());

  String reg = "[.*]";
  String replacingtext = "";
  System.out.println("Text before replacing is:-" 
  itemName
);
  Pattern pattern = Pattern.compile(reg);
  Matcher matcher = pattern.matcher(itemName);
  StringBuffer buffer = new StringBuffer();

  while (matcher.find()) {
  matcher.appendReplacement(buffer, replacingtext);
  }
  int IndexOf = itemName.indexOf(".")
  String domainName = itemName.substring(IndexOf);
  System.out.println("domainName: "+domainName);

  String finalimage = buffer.toString()+"_"+r+domainName;
  System.out.println("Final Image==="+finalimage);

  File savedFile = new File("C:/apache-tomcat-6.0.16/
  webapps/example/"
+"images\\"+finalimage);
  item.write(savedFile);
  out.println("<html>");
  out.println("<body>");
  out.println("<table><tr><td>");
  out.println("<img src=images/"+finalimage+">");
  out.println("</td></tr></table>");

  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "test";
  String driver = "com.mysql.jdbc.Driver";
  String username = "root"
  String userPassword = "root";
  String strQuery = null;
  String strQuery1 = null;
  String imgLen="";

  try {
  System.out.println("itemName::::: "+itemName);
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,username,
  userPassword
);
  Statement st = conn.createStatement();
  strQuery = "insert into testimage set image='"+
  finalimage+
"'"
  int rs = st.executeUpdate(strQuery);
  System.out.println("Query Executed 
   Successfully++++++++++++++"
);
  out.println("image inserted successfully");
  out.println("</body>");
  out.println("</html>");  
  catch (Exception e) {
  System.out.println(e.getMessage());
  finally {
  conn.close();
  }  
  catch (Exception e) {
  e.printStackTrace();
  }
  }
  }
  }
  }
}

 

Download Complete Source Code