tangazo

Retrieve image from database using Servlet

Compile Servlet program

1. Save your file same name as class name.
2. Map your servlet in web.xml file.
3. Open Command Prompt and give appropriate path of your class file.
4.  Compile your servlet class file by using javac file_name.java .
5. Run your program on the Browser by url-pattern which is define in web.xml file.
MySql Table Structure:
CREATE TABLE `pictures` (
`id` int(11) NOT NULL auto_increment,
`image` blob,
PRIMARY KEY (`id`)
)

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

public class DisplayImage extends  HttpServlet{
  public void doGet(HttpServletRequest request, HttpServletResponse 
  response
throws ServletException, IOException{
  //PrintWriter pw = response.getWriter();
  String connectionURL = "jdbc:mysql://192.168.10.59:3306/example";
  java.sql.Connection con=null;
  try{  
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  con=DriverManager.getConnection(connectionURL,"root","root");  
  Statement st1=con.createStatement();
  ResultSet rs1 = st1.executeQuery("select image from"+
   " pictures where id='5'"
);  String imgLen="";
  if(rs1.next()){
  imgLen = rs1.getString(1);
  System.out.println(imgLen.length());
  }  
  rs1 = st1.executeQuery
  (
"select image from pictures where id='5'");
  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();
  }
  }
}

Post a Comment

0 Comments