java 读取数据库图片二进制流并输出到jsp页面

最近刚好遇到这个问题,刚开始在网上各种搜索,看到大量有关该问题的博文。

大量文章有些不敢苟同,希望博主们要写就认真写,请不要浪费其他需要帮助的人的时间去验证你的博文是否正确。

正文如下:

流程说明:

页面点击某条信息---》获取id号---》传人后台进行条件查询----》获取图片二进制流----》转换成图片-----》输出到jsp页面

注:

1.入参:checkNo;//查询条件,根据自己的需求来决定是否需要

2.二进制流只能在本类中传递,由class a中到class b会丢失该流(不知是否正确,本人没有成功。)

--------------------------------action中处理二进制流----------------------------------------

// 在你需要的地方写下如下方法:

/**
  * 选中某个病人,查看报告单信息
  */
public void getReportImageByCheckNo(String checkNo) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
InputStream is = null;
String sql = "select ReportImageBinary from Report where CheckNo = "+ "\'" + checkNo + "\'";
try {
conn = serviceDao.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if(rs.next()){
// 获取报告单二进制流
         is = rs.getBinaryStream("ReportImageBinary");
         is.skip(0);
         showReportImage(is);// 将二进制流显示至JSP页面
}
} catch (Exception e) {
e.printStackTrace();
} finally {
serviceDao.CLOSE(conn, ps, rs);
}
}


/**
 * 根据获取的二进制流,显示图片信息至JSP页面
 * @param is
 */
private void showReportImage(InputStream is) {
OutputStream os = null;
byte buf[] = new byte[1024 * 1024*5]; //定义你需要的缓存大小
HttpServletResponse res =ServletActionContext.getResponse();
res.setContentType("image/*");设置图片的类型.jpeg等类型,此处我用了*,也没报错,是否通配待验证。
    try {
while (is.read(buf) != -1) { 
os = res.getOutputStream();  
   os.write(buf);  
}
} catch (IOException e) {
e.printStackTrace();
}  finally {
if(os != null)
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
if(is != null)
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

--------------------------------------以上是后台处理图片二进制,并输出------------------------------------------


jsp页面:

<%@ page contentType="text/html;charset=gb2312"%>
<html>
<head>
<title>报告单信息</title>
</head>
<body>
<div align="center">
<table border="1" cellpadding="1" cellspacing="1">
<tr>
<td><img src="getReportImageByCheckNo.do?checkNo=<%=request.getParameter("checkNo")%>" align="middle" /> </td> 
</tr>
</table>
<table align="center">
<tr>
<td ><input type="button" οnclick="window.history.back()" value="关闭报告"></td>
<td ><input type="button" οnclick="LoadPic()" value="加载图片"></td>
</tr>
</table>
</div>
</body>
</html>

下篇博文整理了,读取服务器图片地址(说明:图片地址表示该图片存放在服务器的硬盘上,比如d:/xxx/xxx/1.jsp),并在jsp页面展示。

当然此方法也适应读取本地图片,显示在jsp页面。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王大惑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值