this question has answer here:
i trying send images in servlet ajax call showing characters in browser instead. question how encode servlet response in base64
. have image 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+'"/>'); } }); }); });
using
java.util.base64
jdk8byte[] 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: oracle sayssun.*
packages not part of supported, public interface. therefore try prevent using methodsun.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); }
Comments
Post a Comment