最近做个项目使用S2SH和Oracle数据库,其中photo表使用blob类型存储的图片。在网上搜了很多资料,现在把实例代码发一下。
Photo实体类
Photo映射文件
oracle中的blob类型,在实体类中使用java.sql.Blob对应。
从数据库查询数据时正常写查询方法就可以,在页面中输出图片时,在img标签的src属性写要访问的路径,我这里是PhotoAction的thumb方法。
PhotoAction的thumb方法
struts.xml
其中contentType是下载类型,读取的图片所以${contentType}值为image/jpeg。
这样图片就从数据库中读取出来了。以上是使用struts2的方法。如果不使用struts2来实现也可以使用流输出出来。代码如下:
Photo实体类
public class Photo implements java.io.Serializable {
// Fields
private Integer id;
private Album album;
private Date createtime;
private String name;
private String contentType;
private Blob thumbnail;
private Blob content;
private Integer orderid;
private Set facelookmarks = new HashSet(0);
private Set facelookactivities = new HashSet(0);
private Set facelookcomments = new HashSet(0);
/*setter,getter省略*/
}
Photo映射文件
<class name="org.facelook.model.Photo" table="FACELOOKPHOTO" schema="YANGMENG">
/*其他省略*/
<property name="content" type="java.sql.Blob">
<column name="CONTENT" />
</property>
<property name="thumbnail" type="java.sql.Blob">
<column name="THUMBNAIL" />
</property>
oracle中的blob类型,在实体类中使用java.sql.Blob对应。
从数据库查询数据时正常写查询方法就可以,在页面中输出图片时,在img标签的src属性写要访问的路径,我这里是PhotoAction的thumb方法。
[img]photo_thumb?id=<s:property value='photo.id'/>[/img]
PhotoAction的thumb方法
public String thumb(){
try {
this.photo = this.pService.getById(this.id);
this.contentType = this.photo.getContentType();
this.inputStream = this.photo.getContent().getBinaryStream();
} catch (SQLException e) {
e.printStackTrace();
}
return "thumb";
}
struts.xml
<action name="photo_*" class="PhotoAction" method="{1}">
<result name="thumb" type="stream">
<param name="contentType">${contentType}</param>
<param name="bufferSize">1024</param>
</result>
</action>
其中contentType是下载类型,读取的图片所以${contentType}值为image/jpeg。
这样图片就从数据库中读取出来了。以上是使用struts2的方法。如果不使用struts2来实现也可以使用流输出出来。代码如下:
this.photo = this.pService.getById(this.id);
response.setContentType(this.photo.getContentType());//this.photo.getContentType()值为image/jpeg
ServletOutputStream op = response.getOutputStream();
InputStream is = this.photo.getContent().getBinaryStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedImage bi = ImageIO.read(bis);
JPEGImageEncoderImpl jpeg = new JPEGImageEncoderImpl(op);
jpeg.encode(bi);
op.close();
response.flushBuffer();
out.clear();
out = pageContext.pushBody();