0

I want to display an image file on my html page which I am receiving after sending a JQuery post() request to the server as shown in the code below.

I have commented where I am having the issue.

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
  <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>

  <script>
    $.post("http://10.10.129.164:8080/picsOnDemand/sendcphoto/cphoto", {

        clientid: "1234567890",

      },
      function(data) {

        $('#blah').attr('src', data); //What should I code here? 

      });
  </script>
</head>

<body>

  <div data-role="page">
    <div data-role="header">
      <h1>Welcome To My Homepage</h1>
    </div>

    <div id="newimage" data-role="main" class="ui-content">
      <p>I Am Now A Mobile Developer!!</p>
      <img id="blah" src="" height="200" width="200" alt="Image preview...">
    </div>

    <div data-role="footer">
      <h1>Footer Text</h1>
    </div>
  </div>

</body>

</html>

From the server side I am sending an image file in response as shown in the code below:

@Path("/sendcphoto")
public class SendCPhotoRequested {
@POST
@Path("/cphoto")
@Produces("image/jpeg") 
public Response getCPhoto(@FormParam("clientid") String clientid){

     File file = new File("C:\\Users\\nmn\\workspace1\\clientimages\\"+clientid+".jpg");
     System.out.println("File sent");
     ResponseBuilder builder = javax.ws.rs.core.Response.ok((Object) file);
     builder.header("Content-Disposition", "attachment; filename=clientpic.jpg");
    return builder.build();
}
}

Kindly please help, I have been searching for this but I have not got a single answer which worked for me.

AnshX
  • 71
  • 1
  • 1
  • 7

2 Answers2

1

As Adarsh Konchady said, you could return the URL for the image so you can display it with your current code.

You could also return the image content as a base64 string and display it using data URI :

$('#blah').attr('src', 'data:image/jpeg;base64, ' + data);
Community
  • 1
  • 1
Aurel
  • 631
  • 3
  • 18
  • man, when you are just duplicating comments, please, at least, mark them as usefull – or hor Apr 21 '16 at 11:30
  • 1
    I did not duplicate it on purpose, I just saw that the comment had one of the answer I provided sooner than me, so I quote the author. – Aurel Apr 21 '16 at 11:32
1

Convert the image into base64 string and send it to your view .

Base64.encode(FileUtils.readFileToByteArray(file));

and simply set the base64 string in the image src like below.

 $('#blah').attr('src', 'data:image/jpeg;base64, ' + data);
Sagar
  • 818
  • 1
  • 6
  • 13