Books Related to Java Technology

Saturday, January 17, 2009

Insert & Retrieve Image using Servlet

This article show to you how to insert blob type image into mysql database table by using servlet and how to retrieve the image from table and display it on the browser. In this example servlet is used because it dynamically process the request and generate a response for java programming language. The API of the java servlet allow to software developer to add dynamic content to a web server using java. The main advantage of java servlet is, it can be executed to handle request and response objects and it can run independently.

Now, you follow these steps to insert and retrieve image from database table:

1. Create table in your database follow this query:


CREATE TABLE `picture` (
`id` int(10) NOT NULL auto_increment,
`image` blob,
PRIMARY KEY (`id`)
)

2. create a servlet to insert the image:



import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class InsertImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(connectionURL, "root", "");
PreparedStatement ps = con.prepareStatement("INSERT INTO pictures VALUES(?,?)");
File file = new File("C:/images/5.jpg");
FileInputStream fs = new FileInputStream(file);
ps.setInt(1,1);
ps.setBinaryStream(2,fs,fs.available());
int i = ps.executeUpdate();
if(i!=0){
pw.println("image inserted successfully");
}else{
pw.println("problem in image insertion");
}
} catch (Exception e){
System.out.println(e);
}
}
}


3. create web.xml file in WEB-INF folder of your tomcat server and put this code:


<servlet>
<servlet-name>InsertImage</servlet-name>
<servlet-class>InsertImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertImage</servlet-name>
<url-pattern>/InsertImage</url-pattern>
</servlet-mapping>



4. create one more servlet for retrieve image from database table






import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetreiveImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost:3306/test";
java.sql.Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","");
Statement st1=con.createStatement();
ResultSet rs1 = st1.executeQuery("select image from pictures where id='1'");
String imgLen="";
if(rs1.next()){
imgLen = rs1.getString(1);
System.out.println(imgLen.length());
}
rs1 = st1.executeQuery("select image from pictures where id='1'");
if(rs1.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
st1.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
} catch (Exception e){
e.printStackTrace();
}
}
}


5. put this code in to your web.xml file:



<servlet>
<servlet-name>RetreiveImage</servlet-name>
<servlet-class>RetreiveImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RetreiveImage</servlet-name>
<url-pattern>/RetreiveImage</url-pattern>
</servlet-mapping>



6. Compile both servlet file into classes folder by command prompt as:

E:\apache-tomcat-6.0.14\webapps\sandeep\WEB-INF\classes> javac InsertImage.java

and

E:\apache-tomcat-6.0.14\webapps\sandeep\WEB-INF\classes> javac RetreiveImage.java


7. Run your server by startup.bat file


8. Open your browser and type on url address:

http:\\localhost:8080\sandeep\InsertImage

then you will got a success message

9. and then run the RetreiveImage servlet to display your image on browser by

http:\\localhost:8080\sandeep\RetreiveImage

10. Finally you will see the image on your browser


For more details you can visit: http://www.worldinfosoft.com

This is a one of the best tutorial site, where you can find lots of example with full description of code and you van also prepare of your interview from this site WORLDINFOSOFT.COM.

9 comments:

  1. I am very glad to see such examples and the content it is very usefull, and pls keep on that!
    Best Regards!
    Ragi George

    ReplyDelete
  2. nice photo...................!!!!!!!!!!!!!!!

    ReplyDelete
  3. nice one................!!!!!!!!!!!!!!!!!

    ReplyDelete
  4. hiii Sandeeep, its a nice example !
    And the picture is awesome !!!

    ReplyDelete
  5. Hello sandeep ..My problem is not getting the value from the database...my problem is getting the file path from the server machine and display the image... like "c:/upload/folder_name/test.jpg", i want to display the image using servlet, itz working. but the problem is i cant use PrintWriter ..thaz the problem.. i want to display the image inside the div tag. on mouse move over it should retrieve the path from the server and should display it...

    ReplyDelete
  6. gr8 wrk man..!!
    i hope i am not being silly ... but this might be useful for any newbie(like myself)
    1) the table's name should have been 'pictures' and not picture in ur database;
    2)ps.setInt(1,1); and not ps.setInt(1,8);
    3) also use pw.print(e); in each of the catch {} so that it displays the errors for correction.
    4)another obvious mistake was the url... it should have read "jdbc:mysql://localhost:3306/test"

    ReplyDelete
  7. one thing I want to ask you that , how will you show the html portion.

    for example you want to show employee's data with the image , as to put other details , such as id , name , etc.

    hope to get your response
    regards Rupesh

    ReplyDelete