Retrieval Image From DataBase and Display on WebPage by Using Servlets.

Hi Frnds, This Session I will Explain you to "How Retrive Image from DataBase Using Servlets and Display it on WebPage"

The below code is useful for Retrive Image from DataBase Using Servlets and Display it on WebPage.

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.annotation.WebServlet;

@WebServlet("/ImageDis")

public class ImageDis extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)  throws IOException,ServletException
{
 response.setContentType("image/jpeg");

Blob image = null;
Connection con = null;
byte[ ] imgData = null ;
Statement stmt = null;
ResultSet rs = null;

try {

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DbName","UserName","Password");
stmt = con.createStatement();
// Retrieve Image from DataBase using MySQL Query Based on Condition...;
rs = stmt.executeQuery("select imge from empde where id='12'");

if (rs.next()) {
                               //Getting Image From DataBase...;
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());

} else {
System.out.println("Display Blob Example");
System.out.println("image not found for given id>");

}
// display the image...;

ServletOutputStream out1 = response.getOutputStream();
BufferedOutputStream bout = new BufferedOutputStream(out1);
   
bout.write(imgData);

} catch (Exception e) {
System.out.println("Unable To Display image");
System.out.println("Image Display Error=" + e.getMessage());
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Check the OutPut If you have any Doubts Leave your Comments Below...;

Have a Gr8 Day Frnds...;)


EmoticonEmoticon