I am using html,ajax and struts 2 to show image on UI. I am returning response as a byte[] of image from action and when I attach it with the image source then it shows some garbled values.
ajax call I am making from script is
$.ajax({
type: "POST",
url:url,
contentType: "image/png",
success: function(data){
$('.logo').html('<img src="data:image/png;base64,' + data + '" />');
}
} );
and action from where I am returning array of image byte is like this
public void execute(ActionInvocation invocation) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType(action.getCustomContentType());
response.getOutputStream().write(action.getCustomImageInBytes());
}
public byte[] getCustomImageInBytes() {
System.out.println("imageId" + imageId);
BufferedImage originalImage;
try {
originalImage = ImageIO.read(getImageFile("C:\\temp\\Desert.jpg"));
// convert BufferedImage to byte array
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "png", baos);
baos.flush();
imageInByte = baos.toByteArray();
baos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageInByte;
}
I’ve recreated your problem. It does appear to be the base64 encoding, although it works fine in the eclipse local preview without.
Use these two lines instead of response.getOutpuStream().write(…)
My full solution:
HTML
Servlet
Tested