Taufik Pirjade
Taufik Pirjade

Reputation: 430

byte stream image not displaying in browser

Hi I want to display server side image dynamically in browser using ajax.

but images is not coming.

i have checked the server code in debugging mode its working fine but not sure about client code.

readyState coming as 4 but image is not getting displayed.

Server code :

 File f = new File("D:\\mapping events\\Camping\\"+(String) request.getParameter("imageName")+"\\"+"01.jpg");
          DataInputStream dis = new DataInputStream(new FileInputStream(f));
          byte[] barray = new byte[(int) f.length()];

          try 
          { 
            dis.readFully(barray);           // now the array contains the image
          }
          catch (Exception e) 
          { 
            barray = null; 
          }
          finally 
          { 
            dis.close( ); 
          }

          sos.write(barray);                 // send the byte array to client

          System.out.println(barray);
          sos.close();

Ajax code :

 $.ajax({
            url: 'GetCampingImages',
            type: 'POST',
            data:{
                imageName:allData[0]
            },
            cache: true,
            dataType: 'json',
           success: function(jqXHR)
           {
            if(jqXHR)
            {
                if (jqXHR.readyState == 4) {
                $('#dynamicCamping01').html('<img src="data:image/jpeg;'+jqXHR.reresponseText+'"/> ');
                $('#dynamicCampingDesc01').html("<h3>"+allData[0]+"</h3>");
            }
            }
            else
            {
                alert("Something went wrong while retriving events");
            }
        },
        error: function(jqXHR)
        {

           console.log('ERRORS in server: ' );
        }

Upvotes: 0

Views: 901

Answers (1)

Cecilio Pardo
Cecilio Pardo

Reputation: 1717

You should encode the binary data using base64, and use the scheme: "data:image/jpeg;base64,...". Directly sending data bytes is not a good idea for jpeg files.

Upvotes: 1

Related Questions