Java 如何从数据库中检索图像并放置在 JSP 上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4332907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve images from database and place on JSP?
提问by janasainik
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:
我有一个 JSP 页面,它应该从数据库中获取所有图像,并且应该显示在一张表上。我的结果集对象“rs”指向图像。我的代码是这样的:
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 getBinaryStream(), but not succeed. Any idea?
我知道, getString 不适用于 BLOB 类型。我什至用过getBinaryStream(),但没有成功。任何的想法?
采纳答案by Jigar Joshi
Note: Consider this example as reference only to understand the way,
注意:将此示例视为参考,仅用于理解方式,
回答by Bozho
- 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)
- 制作一个 servlet 并将其映射到,例如,
/image/*
- 使用
src="image/<%= imageId %>
,imageId
db中每张图片的唯一id在哪里 - 在 servlet 中
getBinaryStream()
并将其传输(例如使用IOUtils.copy(..)
)到response.getOutputStream()
- 设置
Content-Type
为image/jpeg
或image/png
(或任何类型)
回答by Mohamed Saligh
User the following piece of code to convert Blob to byte[]:
使用以下代码将 Blob 转换为 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:
使用 Servlet 编写您的图像:
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:
使用 jsp 中的 servlet 请求 url 检索您的图像:
<img src="imageDisplayProcess.do?pKey=imageId" width="117" height="160"
onError="loadImage()" onAbort="loadImage()" />
imageDisplayProcess.do?pKey=imageId //should be your image servlet URL
回答by Kedar1442
Just put response type as "image/jpg" and retrieve column using ResultSet
只需将响应类型设置为“image/jpg”并使用 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();
}