You are currently viewing the Servlets section of the Wrox p2p Programmer to Programmer discussion community. This is a community of more than 40,000 computer programmers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining our free Wrox p2p community you can post your own programming questions and respond to other programmers’ questions. Registered users also don't have to see the ads that are displayed to guests. Registration is fast, simple and absolutely free so please, join today!
Join today and post to win prizes! Post more to increase your chances of being Wrox’s top poster of the month.
/**
* Servlet implementation class DisplayBlobExample
*/
public class DisplayBlobExample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DisplayBlobExample() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Blob image = null;
Connection con = null;
Statement stm = null;
ResultSet rs = null;
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/images");
stm = con.createStatement();
rs = stm.executeQuery("select image from picture where pictureid = '2'");
if (rs.next()){
image = rs.getBlob(1);
}
else{
response.setContentType("TEXT/HTML");
out.println("<html><head><title>Display out the blob image</title></head>");
out.println("<body><h4><font color = 'red'>Image not founde for the given id</font></h4></body></html>");
return;
}
response.setContentType("http://p2p.wrox.com/images/jpg");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
public class Image {
int pictureid;
Blob image;
public int getPictureid() {
return pictureid;
}
public void setPictureid(int pictureid) {
this.pictureid = pictureid;
}
public Blob getImage() {
return image;
}
public void setImage(Blob image) {
this.image = image;
}
}
And my jsp page is for calling out the image from servlet is:
Code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="get">
<img src="/DisplayBlobExample"/>
</form>
</body>
</html>
my database is called:
picture.
The attributes are:
pictureid (int)
image(blob)