標籤:style blog color io os ar 檔案 資料 div
近期項目中遇到了這個問題,網上查了一些資料所謂是零零散散,這裡寫篇博文做個筆記。
註:這篇博文中部分類的屬性聲明未列出,應該不算難,基本都是以private 類型 名稱 格式聲明,然後配getter setter方法
首先是圖片入庫的過程,這裡是固定的圖片入庫,項目應用中根據需要可以調整圖片的URL
對應實體類:
1 @Entity 2 @Table(name = "xxx") 3 public class Image { 4 5 private long id; 6 private byte[] photo; 7 8 @Id 9 @Column(name = "ID", unique = true, nullable = false, length = 11)10 public long getId() {11 return id;12 }13 public void setId(long id) {14 this.id= id;15 }16 @Column(name = "PHOTO")17 public byte[] getPhoto() {18 return photo;19 }20 public void setPhoto(byte[] photo) {21 this.photo = photo;22 }23 24 }
入庫方法:(這裡的perDao是用的Hibernate經過一層封裝,基本方法是調用HibernateTemplate中的saveOrUpdate)
1 public void insertPhoto(long id) throws IOException{ 2 Image image = new Image(); 3 File file = new File("E:/workspace/iocs/iocs_bjhy/src/test.png"); 4 InputStream a = new FileInputStream(file); 5 byte[] b = new byte[a.available()]; 6 a.read(b); 7 image.setId(id); 8 image.setPhoto(b); 9 System.out.println(b.length);10 perDao.save(personImage);11 a.close();12 }
接下來是讀取的過程:
頁面代碼:
圖片的src指向返迴流的action,可以帶參數
<img id="empImg" src="person_getPhotoById.action?id=<%=id %>" />
struts2設定檔中的配置如下
<package name="person" extends="json-default"> <action name="person_*" class="personAction" method="{1}"> <result name="getPhotoById" type="stream"> <param name="root">inputStream</param> </result> </action> </package>
action層方法:
public String getPhotoById(){try { Blob blob = Hibernate.createBlob(personService.getPhotoById(id)); inputStream = blob.getBinaryStream(); } catch (Exception e) { e.printStackTrace(); } return "getPhotoById"; }
service層方法:
public byte[] getPhotoById(long id){ List<PersonImage> result = personDao.getPhotoById(id); return result.get(0).getPhoto(); }
dao層方法:
public List getPhotoById(long id){ String hql = "FROM Image WHERE id = ?"; Long[] items = {id}; return perDao.findByHql(hql, items); }
具體方法就是這些,如果有什麼問題或者更好的方案可以留言分享
基於SSH的資料庫中圖片的讀寫