GWT - image from database
I'm actually开发者_如何学JAVA working on a GWT based website. Now I'm stuck on how I should display images stored in a database on my website.
Basically I've a bytearray in my database, which I fetch using hibernate. Now should I probably create an ... tag out of that data, but I don't know how
I'm using GWT in Java and Hibernate
Here is the solution. First you should encode the byte array by using com.google.gwt.user.server.Base64Utils.toBase64(byte[]) . But this method does not work for IE 7. and IE8 has 32kb limit.. IE9 does not have this limit.
here is the method on the server
public String getImageData(){
String base64 = Base64Utils.toBase64(imageByteArray);
base64 = "data:image/png;base64,"+base64;
return base64;
}
Here is the client method ;
@Override
public void onSuccess(String imageData) {
Image image = new Image(imageData);
RootPanel.get("image").add(image);
}
I don't know how GWT works, albeit you can map a servlet/controller which returns resourceStream. For example if you map a servlet "imageViewer" which takes imageId param, request to image would become
/imageViewer?imageId=1234
Hibernate object would have reference to the blob, so you can return that. Reference on UI would be
<img src="/imageViewer?imageId=1234"/>
Update: You may not be able to use Model as it is to return image, you would need an explicit controller or servlet which returns stream data.
In servlet you would do something like
// get reference to input stream
InputStream in = hibnerateObject.getImage();
// set MIME type etc
response.setContentType(mimeType);
OutputStream out = response.getOutputStream();
while ((len = in.read(buf)) >= 0)
out.write(buf, 0, len);
in.close();
out.close();
There is Image Widget in GWT. You can't do it client-side but you can call RPC to communicate with the server. Then it is simple CRUD application. In server connect to database with hibernate and return the Image to the client or it's url and on the client-side do something like that :
@Override
public void onSuccess(String imageUrl) {
Image image = new Image(imageUrl);
RootPanel.get("image").add(image);
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
That's all. Happy coding
I used the same approach as Gursel Koca suggested but could only get it to work using the Apache Base64 library, not (ironically) the GWT Base64Utils
String base64 = Base64.encodeBase64String(array);
base64 = "data:image/"+type+";base64," + base64;
return base64;
Also note that if you are updating an existing image or an image placeholder, the setURL method will overwrite your stylesheet, so make sure to grab that first:
String styleName = profilePicture.getStyleName();
profilePicture.setUrl(base64String);
profilePicture.setStyleName(styleName);
精彩评论