从数据库获得BLOB对象,获得对象后即可关闭Hibernate的 session,在Action中将BOLB的二进制流写入从ServletActionContext获得的response中,设定 response.setContentType( "multipart/form-data" );
注意Action返回的参数应为null.
页面端代码为<img alt="图片显示区域" src="<s:url action="Image"><s:param name="pictureIndex" value="id"></s:param></s:url>">
struts.xml配置的Action为:<action name="Image" class="control.picture.PictureAction" method="dynamicImage"> </action>
Action中的方法为:
public String dynamicImage() throws Exception{
HttpServletResponse response=null;
ServletOutputStream out = null;
InputStream in = null;
byte []bytes = null;
try {
response=ServletActionContext.getResponse();
//二进制输出流
response.setContentType( "multipart/form-data" );
//得到输出流
out = response.getOutputStream();
//得到Blob类实例,使用.getBinaryStream()得到输入流。
//这里的image就是blob类
list=PictureDAO.getList(pictureIndex, 1);
Blob image=list.get(0).getContent();
in = image.getBinaryStream();
//从输入流读取数据到输出流
bytes = new byte [ 1024 ];
while ( -1 != in.read( bytes ) ) {
out.write( bytes );
}
//强制刷新输出流
out.flush();
} catch ( IOException e ) {
e.printStackTrace();
} catch ( Exception e ) {
e.printStackTrace();
} finally {
if ( in != null ) {
try {
in.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
if ( out != null ) try {
out.close();
} catch ( IOException e ) {
e.printStackTrace();
}
bytes = null;
}
return null;
}