2015-09-26 60 views
0

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

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+'"/>'); 
      } 
     }); 
    }); 
}); 

回答

-1
  • 使用java.util.Base64 JDK8

    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.*软件包不是受支持的公共接口的一部分。因此,尽量避免使用此方法

    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); 
    } 
    
+1

我想我需要增加字节的容量,因为图像显示部分。 –

+2

回答很差。 Base64不支持部分编码(由OP的问题“图像部分显示”所证实)。尽管如此,由于http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html – BalusC

+0

中提到的原因,对于“sun.misc.BASE64Encoder”的评价太低了,但是这是以前的散文主义方式jdk8。该方法工作正常。所以不需要任何支持来使用这种方法。 –

相关问题