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

 


 

完。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM