Home Servlets Upload Image using Servlet

Related Tutorials


 
 

Share on Google+Share on Google+

Upload Image using Servlet

Advertisement
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

     

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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 24, 2009

Related Tutorials

Discuss: Upload Image using Servlet   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:10
sameer
April 22, 2011
uoload image

java.io.FileNotFoundException: C:\apache-tomcat-6.0.16\webapps\us\images\Tulips_1301871396.jpg (The system cannot find the path specified) this is my error in this program how to solve
nghia
August 18, 2011
Upload

I see your form has one input tag, if more input tag, your application is running normaly ?
sachin
December 29, 2011
Thanks

Good post
sanket
January 21, 2012
Error Package does not exists

Getting error like -> package org.apache.commons.fileupload.servlet does not exist ----
Neeraj
January 21, 2012
how to upload Images in oracle db with form data

hello; i want to make a web which can store the candidates data and his photos from the form into the oracle db.
Bhagwat Chouhan
February 13, 2012
Thanks

Hi, Thanks for the great tutorial. It saved me from digging for longer time.
raj
April 6, 2012
Exception

"items = upload.parseRequest(request);" is throwing an exception.
sharvari
May 12, 2012
update

I have inserted image but in employee profile update it is not working properly value parameter is not working and not displaying previous photo so plz help me.
JavaIn
November 5, 2012
Thanks

Thanks for the great post.
Ade Hapli
January 6, 2013
library of import org.apache.commons.fileupload.*;

Please explain where u got the library/jar about that.. Thx.. ^_^
DMCA.com