图像/png 响应的原始响应 [英] Raw response of a image/png resonpse

查看:96
本文介绍了图像/png 响应的原始响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个带有原始响应的响应正文,它应该代表一个 png 图像.我的问题是如何解码并使其可渲染.

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:当我使用 postman 来测试时,我意识到 Postman 可以渲染这个原始字符串,我想知道它是如何做到的.

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 dIDATx \ w v,J L 2b _٬ N d 0| cmDN 6 y. q { Iӌ hsnNclg~/;"vʯ m ('} Q9 q P(G: z= q |=_ \ p """""" pw""""""b""""""J PDDDDD A) 8(B @(""""" EDDDDD RqP""""""J PDDDDD A) 8(B @(""""" EDDDDD R
[...]

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
[...]

推荐答案

经过几个小时的谷歌搜索,我终于找到了问题所在:本质上,来自我的 REST 调用的响应实际上包含 blob 类型的 png 图像.因此,为了正确渲染它,我们不必对 blob 进行 base64,而是由 html5 本身支持.我面临的问题是 jQuery ajax 调用不支持这个 blob,因此像 axios 这样的高级库也不支持它.

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.

为了简单起见,为了演示这是如何工作的,我将使用 jQuery:

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>

这篇关于图像/png 响应的原始响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆