开发者

How to retrieve images from database and place on JSP? [duplicate]

This question already has answers here: How to retrieve and display images from a database in a JSP page? (6 answers) Closed 8 years ago.

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,


  1. Make a servlet and map it, to, say, /image/*
  2. Use src="image/<%= imageId %>, where imageId is the unique id of each image in the db
  3. in the servlet getBinaryStream() and transfer it (for example using IOUtils.copy(..)) to response.getOutputStream()
  4. Set the Content-Type to image/jpeg or image/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();
       }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜