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);
    }
}

 


 

完。

 

posted @ 2017-03-01 11:02  Tiac  阅读(26989)  评论(0编辑  收藏  举报