Search code examples
javajsonajaxbase64bufferedinputstream

how to write encoded stream in JSON and retrieve back in ajax?


I am geeting image in input stream and encoding it into base64 and sending it to client using JSON Following is code snippet.

Server side :

 JsonObject myObj = new JsonObject();
    StringBuilder responseStrBuilder = new StringBuilder();
    int ch =0; ;        
    sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
    byte[] contents = new byte[5000000];
    int bytesRead = 0;
    String strFileContents;
    while ((bytesRead = bin.read(contents)) != -1) {
        responseStrBuilder.append(encoder.encode(contents).getBytes());
    }
    myObj.addProperty("1",responseStrBuilder.toString());
    out.println(myObj.toString());

Client side ajax code :

success: function(result)
           {
            if(result)

            {
                $('#dynamicCamping01').html('<img src='+result[Object.keys(result)[0]]+'/>');
                $('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
            }
            else
            {
                alert("Something went wrong while retriving events");
            }

getting data at client side but image is not displaying.


Solution

  • This one worked :

       BufferedInputStream bin = new BufferedInputStream(fin);  
    
        BufferedOutputStream bout = new BufferedOutputStream(out);  
        int ch =0; ;  
    
        sun.misc.BASE64Encoder encoder= new sun.misc.BASE64Encoder();
        byte[] contents = new byte[5000000];
        int bytesRead = 0;
        String strFileContents;
        while ((bytesRead = bin.read(contents)) != -1) {
            bout.write(encoder.encode(contents).getBytes());
        }
        bout.close();
        fin.close();
        bin.close();
        out.close();
    

    and main important part is on client converting image into UTF-8 and Base64 decoding.

    $(imageIDSData[i]).html('<img src="data:image/jpeg;charset=utf-8;base64,'+imageData[i]+'"/> ');
        $(imageNameIDSData[i]).html("<h3>"+allData[i]+"</h3>");