Here is the scenario. You have images stored in database, and you want to use these images in your gwt application. As already known, the gwt image object constructor takes only String , this string should represent the url of the image.. You can construct the image in the server, and you can save this image to your server's disk, and you can use the url of this image . But , this solution is not elegant, you have to save image to the server's disk..
As a second solution, you can write a servlet whose purpose is to fetch images from database and send them to the clients.. You can map this servlet ImageViewer , with a parameter. The request looks like this ;
/imageViewer?imageId=1234 . You should create your gwt image widget like below;
Image image = new Image( "/imageViewer?imageId=1234");
ImageViewer servlet doGet method should be like that ;
public void doGet(HttpServletRequest request, HttpServletResponse response) {
String imageId = request.getParameter("imageId");
byte[] imageData = readImageDataFromDB(imageId);
response.setContentType("image/png");
response.getOutputStream().write(imageData,0,imageData.length);
}
As a third solution , you can use the below code to convert image byte array data, to Base64 encoded string.. But you should know that this method does not work for IE7 and the previous versions. IE8 has 32 kb limit for encoded data.
public String getImageData(){
byte[] imageByteArray = readImageDataFromDB(); //
String base64 = com.google.gwt.user.server.Base64Utils.toBase64(imageByteArray);
base64 = "data:image/png;base64,"+base64;
return base64;
}
And at gwt layer, you should use the below code ;
imageService.getImageData(new AsyncCallback() {
@Override
public void onSuccess(String imageData) {
Image image = new Image(imageData);
RootPanel.get("image").add(image);
}
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
}