hula100

使用JavaScript调用API返回了二进制数据格式的图片,该如何显示到网页上?

首先,直接使用XMLHttpRequest,而不是AJAX,原因已经在前一篇文章中解释。并将responseType设置为arraybuffer

var xhr = new XMLHttpRequest();
xhr.open(\'GET\', \'/my/image/name.png\', true);
xhr.responseType = \'arraybuffer\';

然后,将二进制转成图片源,我从网上搜索找到以下两种方法,大家可以随意选择自己喜欢的。

方法一

var uInt8Array = new Uint8Array(xhr.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--) {
    binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join(\'\');

var imageType = xhr.getResponseHeader("Content-Type");
$(\'#image\').attr("src", "data:" + imageType + ";base64," + data)

方法二

var imageType = xhr.getResponseHeader("Content-Type");
var blob = new Blob([xhr.response], { type: imageType });
var imageUrl = (window.URL || window.webkitURL).createObjectURL(blob);
$(\'#image\').attr("src", imageUrl);

 

分类:

技术点:

相关文章:

  • 2021-04-03
  • 2021-06-12
  • 2021-09-21
  • 2021-12-15
  • 2021-11-01
  • 2021-11-22
  • 2021-10-14
  • 2021-08-15
猜你喜欢
  • 2021-09-05
  • 2021-12-03
  • 2021-06-28
  • 2021-11-15
  • 2021-11-23
  • 2021-11-13
相关资源
相似解决方案