4

我正在使用 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;
  }
4

1 回答 1

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>

小服务程序

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;
    }
}

经过测试

  • Chrome 版本 23.0.1271.97 OSX 10.7.5
  • 火狐 16.0.2 OSX 10.7.5
  • Safari 6.0.2 OSX 10.7.5
于 2012-12-19T07:27:19.697 回答