从http get请求显示PNG

时间:2017-10-29 14:24:46

标签: javascript angular http

我正在使用角度4,我使用api返回带有内容类型的图像:img / png

http方法:

return this.http.get('URL', this.options)
    .map((res: Response) => res.text());
// can be also : res.arrayBuffer() // res.blob()

http get响应(在文本和ARC中)是这样的:

�PNG  IHDR��"͹�W�W��zؽ�|+q%�   ��Y������M缥{��U��H�ݏ)L�L�~�6/'6Q׌�}���:��l'���� �R�L�&�~Lw?�

我尝试了不同的方法来转换它并显示它:

  • blob 获取响应并使用以下命令进行转换:

     new Uint8Array(response)
    
  • 将图像设为 arrayBuffer ,然后使用以下命令进行转换:

      arrayBufferToBase64(buffer) {
      let binary = '';
      let bytes = new Uint8Array(buffer);
      let len = bytes.byteLength;
      for (let i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
     }
    

他们两个都没有为我工作,图像没有显示。

我的问题是,响应的真实格式是什么(blob,arraybuffer或text)以及如何显示它?

1 个答案:

答案 0 :(得分:2)

您可以使用fetch API实现此目的。

让我们首先将回复作为blob返回。 然后,您可以使用URL.createObjectURL()创建文件对象。

fetch(URL)
  .then(res=>{return res.blob()})
  .then(blob=>{
    var img = URL.createObjectURL(blob);
    // Do whatever with the img
    document.getElementById('img').setAttribute('src', img);
  })

https://stackoverflow.com/a/33915898/8751565