0

I was trying to send the images in servlet to ajax call but its showing some characters in my browser instead. my question is how to encode servlet response in base64. I have an image as response.

Servlet code :

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 code :

$(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+'"/>');
            }
        });
    });
});
Sully
  • 14,672
  • 5
  • 54
  • 79
Taufik Pirjade
  • 380
  • 6
  • 26

1 Answers1

-1
  • Using 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);
    }
    
  • Using sun.misc.BASE64Encoder, Note that: The Oracle says that the sun.* packages are not part of the supported, public interface. Therefore try to prevent using this method

    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());
    }
    
  • Using 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);
    }
    
Channa Jayamuni
  • 1,876
  • 1
  • 18
  • 29
  • 1
    I think i need to increase byte capacity because image is displaying partially. – Taufik Pirjade Sep 26 '15 at 09:37
  • 2
    Poor answer. Partial encoding isn't supported by Base64 (as confirmed by OP's problem "Image is displaying partially"). Nonetheless, a fat downvote for `sun.misc.BASE64Encoder` for reasons mentioned in http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html – BalusC Sep 26 '15 at 10:03
  • yes, however it was the essayist way before jdk8. that method works fine. so no need any support to use this method. – Channa Jayamuni Sep 26 '15 at 10:11