圖片類: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”