Hibernate 对数据库Blob图片的查询操作---页面显示图片,文件的输出
怎样使用hibernate上传和更新图片在我的另一篇文章有所介绍,请参看 http://blog.csdn.net/fhway/archive/2006/11/01/1359482.aspx 在这里讲的是如何查询得到结果的问题
1.在jsp页面里输出,通常的做法是建立一个servlet的方式,我要讲的也是这个方法;代码如下;
/**
*
*/
package com.sclh.hibernate.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sclh.common.ChineseString;
import com.sclh.hibernate.HibernateSessionFactory;
import com.sclh.hibernate.bean.Zp;
import com.sclh.hibernate.service.ZpService;
/**
* @author fuhw
*
*/
public class ShowImageServlet extends HttpServlet {
private static final Log log = LogFactory.getLog(ShowImageServlet.class);
String rybh = "";
String zpxh = "";
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("ShowImageServlet come in!");
HttpSession session = (HttpSession) request.getSession();
request.setCharacterEncoding("ISO8859-1");
rybh = ChineseString.chineseStr((String) request.getParameter("rybh"));
zpxh = ChineseString.chineseStr((String) request.getParameter("zpxh"));
Zp zp = new Zp();
ZpService service = new ZpService();
String id = service.queryZpIdByRybhAndZpxh(rybh, Integer.valueOf(zpxh));
org.hibernate.Session hibernateSession = HibernateSessionFactory
.getCurrentSession();
try {
zp = (Zp) hibernateSession.load(Zp.class, Integer.valueOf(id));
if(!zp.getPic().equals(null)){
Blob photo = zp.getPic();
InputStream in = photo.getBinaryStream();
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
}else{
//可以展示的其他照片
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
<td width="32%" bgcolor="#FFFFFF"><IMG id=personpic
height=231 alt="" src="/ShowImageServlet?rybh=<%=rybh%>&zpxh=2"
width=183 name=personpic></td>
哈哈,就可以了;
2.文件的输出
public void queryZp(Integer id, String filePath) {
log.debug("queryZp instance");
Session session = null;
try {
session = getSession();
Zp zp = (Zp) session.load(Zp.class, id);
System.out.println(zp.getId().toString());
InputStream is = ((java.sql.Blob)zp.getPic()).getBinaryStream();
OutputStream os = new FileOutputStream(filePath);
byte[] byteBuffer = new byte[10240];
int len;
while ((len = is.read(byteBuffer)) != -1) {
os.write(byteBuffer, 0, len);
}
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
session.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}


浙公网安备 33010602011771号