Recent projects encountered this problem, the online search for some information called fragmented, here write a blog to make a note.
Note: The attribute declarations in the middle of this blog post are not listed and should not be difficult, basically in the private type name format declaration, and then with the Getter setter method
The first is the picture storage process, here is a fixed picture storage, Project application can adjust the image URL as needed
Corresponding entity classes:
1 @Entity2@Table (name = "XXX"))3 Public classImage {4 5 Private LongID;6 Private byte[] photo;7 8 @Id9@Column (name = "ID", unique =true, nullable =false, length = 11)Ten Public LonggetId () { One returnID; A } - Public voidSetId (LongID) { - This. id=ID; the } -@Column (name = "PHOTO") - Public byte[] Getphoto () { - returnphoto; + } - Public voidSetphoto (byte[] photo) { + This. Photo =photo; A } at -}
Storage method: (Here The Perdao is used hibernate through a layer of encapsulation, the basic method is to call Hibernatetemplate in the Saveorupdate)
1 Public voidInsertphoto (LongIdthrowsioexception{2Image image =NewImage ();3File File =NewFile ("E:/workspace/iocs/iocs_bjhy/src/test.png");4InputStream A =Newfileinputstream (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);Ten Perdao.save (personimage); One a.close (); A}
The next step is the read process:
Page code:
The src of the image points to the action that returns the stream, with parameters
<id= "empimg" src= "Person_getphotobyid.action?id=<%=id%>" />
The configuration in the Struts2 configuration file is as follows
< Packagename= "Person"extends= "Json-default"> <Actionname= "Person_*"class= "Personaction"Method= "{1}"> <resultname= "Getphotobyid"type= "Stream"> <paramname= "root">InputStream</param> </result> </Action> </ Package>
Action Layer Method:
Public String Getphotobyid () {try { = Hibernate.createblob (Personservice.getphotobyid ( ID)); = Blob.getbinarystream (); Catch (Exception e) { e.printstacktrace (); } return "Getphotobyid"; }
Service Layer Method:
Public byte [] Getphotobyid (long id) { List<PersonImage> result = Persondao.getphotobyid (ID); return result.get (0). Getphoto (); }
DAO Layer Method:
Public List Getphotobyid (long id) { = "from Image WHERE id =?" ; = {id}; return perdao.findbyhql (hql, items); }
The specific method is these, if there is any problem or better solution can be a message to share
Read and write images in an SSH-based database