工做中经常使用到接口生成图片,返回的数据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;