本文參照如下兩篇:
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);
}