0

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: ' );
        }
Taufik Pirjade
  • 380
  • 6
  • 26
  • You can check if your server side code working by pointing your browser to link which you're going to download, your image should be displayed in a browser. I didn't check your code but I think that problem in a server side. Look at this code for example http://stackoverflow.com/questions/2979758/writing-image-to-servlet-response-with-best-performance – Anatoly Jan 04 '16 at 23:38

1 Answers1

1

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.

Cecilio Pardo
  • 1,717
  • 10
  • 13
  • I haven't tested the code, but I know you need to use base64 to encode the image, so that it is text. HTML needs it to be text. – Cecilio Pardo Jan 04 '16 at 22:15