js 获取图片url的Blob值并预览

时间:2023-03-09 17:25:43
js 获取图片url的Blob值并预览

1)使用 XMLHttpRequest 对象获取图片url的Blob值

//获取图片的Blob值
function getImageBlob(url, cb) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status == 200) {
if(cb) cb(this.response);
}
};
xhr.send();
}

注意这里的XMLHttpRequest必须使用异步模式,同步模式不能设置 responseType = "blob"

2)使用 FileReader 对象获取图片 Blob 对象的 data 数据

function preView(url){
let reader = new FileReader(); getImageBlob( url , function(blob){
reader.readAsDataURL(blob);
}); reader.onload = function(e) {
var img = document.createElement("img");
img.src = e.target.result;
document.body.appendChild(img);
}
}

完。