Skip to content Skip to sidebar Skip to footer

Raw Response Of A Image/png Resonpse

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 t

Solution 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:

<htmllang="en"><head><metacharset="utf-8"><title>Blob image/png demo</title><scriptsrc="https://code.jquery.com/jquery-1.10.2.js"></script></head><body><formaction="/"id="invokeBlob"><inputtype="submit"value="Invoke It!"></form><!-- the result of the blob will be rendered inside this div --><divid="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 = newXMLHttpRequest();
    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>

Post a Comment for "Raw Response Of A Image/png Resonpse"