2015-09-26 59 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。該方法工作正常。所以不需要任何支持來使用這種方法。 –

相關問題