JavaScript使用XMLHttpRequest实现图片加载显示进度

142 2020-12-16 07:16:30 var xhr = new XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress (上传中干点事)
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress(下载中中干点事)
console.log(percentComplete);
}
}, false);
xhr.open('GET','http://easysart.oss-cn-shenzhen.aliyuncs.com/images/artwork/1000/2018-10-24_0938325bcfcd18f2e36.jpg', true);
xhr.responseType = "blob";
xhr.setRequestHeader("client_type", "DESKTOP_WEB");
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
console.log(blob);
var img = document.createElement("img");
img.onload = function(e) {
window.URL.revokeObjectURL(img.src);
};
img.src = window.URL.createObjectURL(blob);
$("#img").html(img);
}
}
xhr.send();