ajax返回图片类型,ajax接口返回图片类型数据,转为base64赋值给img

  • Post author:
  • Post category:其他


工做中经常使用到接口生成图片,返回的数据JS怎么处理转成base64展现?javascript

主要利用xhr2.0,responseType=”blob”返回blob数据类型,代码以下:

第一种:html

function fetchImageDataFromUrl(url, cb) {

var xhr = new XMLHttpRequest();

xhr.open(“GET”, url, true);

xhr.responseType = “blob”;

xhr.withCredentials = true;

xhr.onload = function() {

if (xhr.status < 400)

cb(this.response, null);

else

cb(null, “HTTP Status ” + xhr.status + ” for url ” + url);

}

xhr.onerror = function(e) {

cb(null, e);

}

xhr.send();

}

fetchImageDataFromUrl(url, function () {

var reader = new FileReader();

reader.onload = function (event) {

var txt = event.target.result;