我正在使用 html、ajax 和 struts 2 在 UI 上显示图像。我将响应作为来自动作的图像的字节 [] 返回,当我将它与图像源附加时,它会显示一些乱码值。
我从脚本进行的 ajax 调用是
$.ajax({
type: "POST",
url:url,
contentType: "image/png",
success: function(data){
$('.logo').html('<img src="data:image/png;base64,' + data + '" />');
}
} );
我从哪里返回图像字节数组的动作是这样的
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;
}