How to retrieve images from database and place on JSP? [duplicate]
I have a JSP page and it should get all the images from database and should to display on one table. My resultset object 'rs' is pointing to images. My code is like this:
String query = "select image from stock";
rst = stmt.executeQuery(query);
while(rst.next())
<%
<td><img height="89" src=<%rst.getString(1)%></td>
%>
}
I know, getString will not work for BLOB type. I was even used getBinarySt开发者_如何学Goream(), but not succeed. Any idea?
User the following piece of code to convert Blob to byte[]:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
InputStream in = blob.getBinaryStream();
int n = 0;
while ((n=in.read(buf))>=0)
{
baos.write(buf, 0, n);
}
in.close();
byte[] bytes = baos.toByteArray();
Use Servlet to write your image:
if (bytes != null && bytes.length > 0) {
response.setContentType("image/jpg");
response.getOutputStream().write(bytes);
response.getOutputStream().flush();
response.getOutputStream().close();
}
Use retrive your image using servlet request url in jsp:
<img src="imageDisplayProcess.do?pKey=imageId" width="117" height="160"
onError="loadImage()" onAbort="loadImage()" />
imageDisplayProcess.do?pKey=imageId //should be your image servlet URL
Here is complete example ,
Note: Consider this example as reference only to understand the way,
- Make a servlet and map it, to, say,
/image/*
- Use
src="image/<%= imageId %>
, whereimageId
is the unique id of each image in the db - in the servlet
getBinaryStream()
and transfer it (for example usingIOUtils.copy(..)
) toresponse.getOutputStream()
- Set the
Content-Type
toimage/jpeg
orimage/png
(or whatever the type is)
Just put response type as "image/jpg" and retrieve column using ResultSet
demo code written bellow---
if(rs.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
精彩评论