js請求後臺接口返回的圖片並轉爲base64

本文參照如下兩篇:

https://www.cnblogs.com/cdemo/p/5225848.html

https://www.cnblogs.com/dcb3688/p/4608062.html

 

使用html5 獲取圖片blob

var url = "http://****";
var xhr = new XMLHttpRequest();    
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
	if (this.status == 200) {
        var blob = this.response;
        console.log(blob);
	} 
}
xhr.send();

blob轉爲base64

/**
 * 
 * blob二進制 to base64
 **/
function blobToDataURI(blob, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        callback(e.target.result);
    }
    reader.readAsDataURL(blob);
}


blobToDataURI(blob, function (data) {
    console.log(data);  //data已經是base64
    $('#serviceImage').attr("src",data);
});

完整代碼

var url = "http://****";
var xhr = new XMLHttpRequest();    
xhr.open("get", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
    if (this.status == 200) {
        var blob = this.response;
        blobToDataURI(blob, function (data) {
            console.log(data);
            $('#serviceImage').attr("src",data);
        });
    } 
}
xhr.send();

/**
 * 
 * blob二進制 to base64
 **/
function blobToDataURI(blob, callback) {
    var reader = new FileReader();
    reader.onload = function (e) {
        callback(e.target.result);
    }
    reader.readAsDataURL(blob);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章