jsp从数据库读取Blob类型的图片
首先为什么要这么做,以前Blob值是写入一个javabean中的对象,但是Bolb抛出空指针。
原因是在查找出用户信息后对数据库进行了关闭,那么当然流不能从数据库中流了。
解决办法重新查找数据库,在关闭数据库之前通过流来实现图片显示。
通过
<%@ page import="java.io.InputStream,
java.io.OutputStream,
com.seipher.dao.UserInfoDAO,
com.seipher.pojo.UserInfo,
com.seipher.common.ToolKit,
java.sql.*”%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<%
String user=(String)session.getAttribute(“user”);
ToolKit toolKit=new ToolKit();
String sql=”Select * From FTMEDB.NormalUser Where UserID = ?”;
System.out.println(sql);
Connection cn=null;
cn=toolKit.openConn();
try {
PreparedStatement smt = cn.prepareStatement(sql);
smt.setString(1,user);
ResultSet rs=smt.executeQuery();
if (rs.next()) {
InputStream inStream = null;
OutputStream output = null;
Blob blob = rs.getBlob(“PHOTO”);
try{
if (blob != null || !blob.equals(null))
{
inStream= blob.getBinaryStream();
//设置输出的格式
response.reset();
response.setContentType(“image/gif”);
if ( blob.length() != 0 ) {
response.setContentLength((int)blob.length());
}
// response.addHeader(“Content-Disposition”,”attachment; filename=”” +new String(filename.getBytes(“gb2312″),”iso8859-1”) + “””);
//循环取出流中的数据
byte[] b = new byte[1024];
int len;
output = response.getOutputStream();
while((len=inStream.read(b)) >0)
output.write(b,0,len);
}else{
out.print(“不存在该文件或被删除”);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if ( inStream !=null ) {
inStream.close();
inStream = null;
}
if ( output != null ) {
output.close();
output = null;
}
}
}
rs.close();
rs=null;
smt.close();
smt=null;
} catch (SQLException e) {
e.printStackTrace();
}finally {
try{
cn.close();
cn = null;
}catch(Exception e) {
}
}
%>
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《jsp从数据库读取Blob类型的图片》
本文地址:http://www.xiupu.net/archives-337.html
关注公众号:
微信赞赏
支付宝赞赏