我使用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;
}
如果你沒有在任何地方編碼爲base64或者在outstream上寫write()是免費的嗎? – Adam
是否需要在java端編碼到base64,因爲我在腳本端處理它? – ankit