图片类:picture.java
public class Picture implements java.io.Serializable {
private String pictureid;
private String picversion;
private String kind; //图片类型:光学图片、遥感图片等
private byte[] picture; //图片字节数组
……
hibernate文件:
<hibernate-mapping>
<class name="org.military.po.Picture" table="picture" schema="MilitaryMS">
<id name="pictureid" type="string">
<column name="pictureid" length="100" />
<generator class="assigned" />
</id>
<property name="picversion" type="string">
<column name="picversion" length="100" not-null="true" />
</property>
<property name="kind" type="string">
<column name="kind" length="50" not-null="true" />
</property>
<property name="picture" type="binary">
<column name="picture" />
</property>
</class>
</hibernate-mapping>
实现功能将指定目录下的图片保存到数据库中,关键代码:
所有的图片路径都存放在session参数imagesPath中,依次取出所有路径,将该路径下的文件保存入数据库中。
Map<String,String> imagesPath=(HashMap<String,String>) ActionContext.getContext().getSession().get("imagesPath");
Iterator itr= imagesPath.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String,String> entry=(Entry<String, String>) itr.next();
String imagepath=entry.getKey();
String type=entry.getValue();
FileInputStream fin;
byte[] buffer=new byte[1024];
int len=0;
try {
fin=new FileInputStream(imagepath);
ByteArrayOutputStream fos=new ByteArrayOutputStream();
while((len=fin.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
pictureService.savePicture(new Picture(imagepath,shipversion,type,fos.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
}
}
在jsp中显示图片
jsp页面显示
<img data-src= "holder.js/300x200" src= '<%=path%>/imageShowAction?version= <s:property value= "version" /> ' onError= "this.src='./image/nopic.jpg'" alt= "Generic placeholder thumbnail" style=" width: 330px; height : 220px;">
struts配置文件:
<action name= "imageShowAction" class ="imageUploadAction" method= "showImage">
<result name= "null" type ="stream">
<param name="contentType" >image/ jpeg,image/bmp ,image/png,image/ gif,image/jpeg ,image/pjpeg</param >
</result>
</action>
注意其中的name必须为null。
action类:
public class ImageUploadAction extends ActionSupport
{
private PictureService pictureService ;
private String version ;
private HttpServletResponse response ;
private ServletOutputStream sout ;//二进制流可以直接在 jsp页面显示
get和set函数……
public String showImage() {
Picture picture = pictureService.queryOnePicByVersion(version );
byte[] pic=null ;
if(picture!=null){
pic=picture.getPicture();
response=ServletActionContext. getResponse();
response.setContentType( "image/jpeg");
try {
sout= this.response .getOutputStream();
sout.write(pic,0,pic. length);
sout.flush();
sout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null ;
}
}
注意该处的返回值为null。对应配置文件中的name=“null”