原文鏈接 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
}
});