在 post() 请求后在 jquery 中显示图像

Displaying image in jquery after post() request

本文关键字:显示 显示图 图像 jquery post 请求      更新时间:2023-09-26

我想在我的html页面上显示一个图像文件,这是我在向服务器发送JQuery post()请求后收到的,如下面的代码所示。

我已经评论了我遇到问题的地方。

<!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>

从服务器端,我正在发送一个图像文件作为响应,如下面的代码所示:

@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();
}
}

请帮忙,我一直在寻找这个,但我没有得到一个对我有用的答案。

正如Adarsh Konchady所说,您可以返回图像的URL,以便可以使用当前代码显示它。

您还可以将图像内容作为 base64 字符串返回,并使用数据 URI 显示它:

$('#blah').attr('src', 'data:image/jpeg;base64, ' + data);

将图像转换为 base64 字符串并将其发送到您的视图。

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

只需在图像 SRC 中设置 base64 字符串,如下所示。

 $('#blah').attr('src', 'data:image/jpeg;base64, ' + data);