原文链接 https://segmentfault.com/q/1010000011113418
js 怎么判断文件或图片下载的进度?
简单的示例:
xhr.loaded
表示已经下载多少xhr.total
表示总共多少
做个除法即可
(下面示例仅举例如何监听progress)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', './1.html');
xhr.onprogress = function (event) {
if (event.lengthComputable) {
console.log(event.loaded);
console.log(event.total);
}
};
xhr.send();
</script>
</html>
JQUERY方案
$.ajax({
xhr: function()
{
var xhr = new window.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);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data){
//Do something success-ish
}
});