如何编码 servlet 对 base64 的响应?

how to encode servlet response to base64?

我试图将 servlet 中的图像发送到 ajax 调用,但它在我的浏览器中显示了一些字符。 我的问题是如何在 base64 中编码 servlet 响应。 我有一张图片作为回应。

Servlet 代码:

response.setContentType("image/jpeg");
ServletOutputStream out;  
out = response.getOutputStream();
FileInputStream fin = new FileInputStream("D:\Astro\html5up-arcana (1)\images\1.jpg");

BufferedInputStream bin = new BufferedInputStream(fin);  
BufferedOutputStream bout = new BufferedOutputStream(out);  
int ch =0; ;  
while((ch=bin.read())!=-1) {  
    bout.write(ch);  
}  

Ajax代码:

$(document).ready(function() {
    $('#nxt').click(function() {
        $.ajax({
            url : 'DisplayImage',
            data : {
                userName : 'Hi'
            },
            success : function(result) {
                $('#gallery-overlay').html('<img src="data:image/jpeg;base64,'+result+'"/>');
            }
        });
    });
});
  • 使用java.util.Base64JDK8

    byte[] contents = new byte[1024];
    int bytesRead = 0;
    String strFileContents;
    while ((bytesRead = bin.read(contents)) != -1) {
        bout.write(java.util.Base64.getEncoder().encode(contents), bytesRead);
    }
    
  • 使用sun.misc.BASE64Encoder,注意:Oracle说sun.*包不在支持范围内,public 界面。因此尽量避免使用这种方法

    sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
    byte[] contents = new byte[1024];
    int bytesRead = 0;
    String strFileContents;
    while ((bytesRead = bin.read(contents)) != -1) {
        bout.write(encoder.encode(contents).getBytes());
    }
    
  • 使用org.apache.commons.codec.binary.Base64

    byte[] contents = new byte[1024];
    int bytesRead = 0;
    while ((bytesRead = bin.read(contents)) != -1) {
        bout.write(org.apache.commons.codec.binary.Base64.encodeBase64(contents), bytesRead);
    }