我使用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;
}
答案 0 :(得分:3)
我重新创建了你的问题。它看起来似乎是base64编码,虽然它在没有的eclipse本地预览中工作正常。
使用这两行而不是response.getOutpuStream()。write(...)
String encoded = javax.xml.bind.DatatypeConverter
.printBase64Binary(action.getCustomImageInBytes());
response.getOutputStream().print(encoded);
我的完整解决方案:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Dynamic image test - stackoverflow issue 13946908</title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
</head>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url : "/Test/ImageServer",
contentType : "image/png",
success : function(data) {
$('.logo').html('<img src="data:image/png;base64,' + data + '" />');
}
});
});
</script>
<body>
<div class="logo"></div>
</body>
</html>
的Servlet
public class ImageServer extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("image/jpeg");
byte[] data = getCustomImageInBytes(request.getServletContext()
.getResource("/horse.jpg"));
String encoded = DatatypeConverter.printBase64Binary(data);
response.getOutputStream().print(encoded);
}
private byte[] getCustomImageInBytes(URL url) throws IOException {
BufferedImage originalImage = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
return imageInByte;
}
}
测试