Raw response of a image/png resonpse

隐身守侯 提交于 2021-01-28 04:45:11

问题


I am getting a response body with raw response, which is supposed to respresent a png image. My question is how to decode this and make it a renderable.

PS: when I am use postman to test this, I realized that Postman can render this raw string, and I am wondering how it does it.

�PNG

IHDR�X:�(� pHYs���o�d IDATx���\�w����v,J�L�2b�_٬�N��d��0|�cmDN�6�y.�q�{�Iӌ�hsnNcl��g~/;"vʯ�m�('}�Q9��q�P(G:�������z=���q��|=_�\�p�""""""�p�w""""""b �""""""J�PDDDDD�A)������8(B�@("""""�EDDDDD���������R qP �""""""J�PDDDDD�A)������8(B�@("""""�EDDDDD���������R
[...]


回答1:


After a few hours of googling, I finally figured out the issue: Essentially, the response from my REST call actually contains blob type of the png image. So to properly render it, we don't have to base64 the blob, instead it is natively supported by html5. The problem I was facing is that this blob is not supported by jQuery ajax call, hence higher level libraries like axios does NOT support it either.

For simplicity, to demo how this works, I would use jQuery:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Blob image/png demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<form action="/" id="invokeBlob">
  <input type="submit" value="Invoke It!">
</form>
<!-- the result of the blob will be rendered inside this div -->
<div id="imgcontainer"></div>

<script>
  // Attach a submit handler to the form
  $( "#invokeBlob" ).submit(function( event ) {

    // Stop form from submitting normally
    event.preventDefault();

    var url = "https://YOUR-DOMAIN/charts";
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = "blob";

    xhr.setRequestHeader("Authorization", "Bearer XXX-YOUR-JWT-TOKEN")
    xhr.setRequestHeader("Accept", "image/png");
    xhr.onload = function() {
      if (this.status == 200) {
        var blob = this.response;
        var img = document.createElement("img");
        img.onload = function(e) {
          window.URL.revokeObjectURL(img.src);
        };
        img.src = window.URL.createObjectURL(blob);
        $("#imgcontainer").html(img);
      }
    }
    xhr.send();
  });
</script>

</body>
</html>


来源:https://stackoverflow.com/questions/54210068/raw-response-of-a-image-png-resonpse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!