基於SSH的資料庫中圖片的讀寫

來源:互聯網
上載者:User

標籤: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的資料庫中圖片的讀寫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.