const handler = HttpProgressHandler()
axios.get('/download?ID=12345', {
onDownloadProgress: function (e) {
const { speed, percent, completed } = handler(e)
console.log(completed + 'MB (' + percent + '%) ' + speed + 'KB/s')
}
})
Last active
April 28, 2021 04:02
-
-
Save socheatsok78/c573b573b4adafa43da163df3843aaa9 to your computer and use it in GitHub Desktop.
MLHttpRequest: progress event handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function HttpProgressHandler () { | |
let lastNow = new Date().getTime() | |
let lastKBytes = 0 | |
return function onHttpProgressHandler (e) { | |
if (!e.lengthComputable) return | |
const now = new Date().getTime() | |
const bytes = e.loaded | |
const total = e.total | |
const percent = bytes / total * 100 | |
const kbytes = bytes / 1024 | |
const mbytes = kbytes / 1024 | |
const uploadedkBytes = kbytes - lastKBytes | |
const elapsed = (now - lastNow) / 1000 | |
const kbps = elapsed ? uploadedkBytes / elapsed : 0 | |
lastKBytes = kbytes | |
lastNow = now | |
return { | |
speed: kbps.toFixed(2), | |
percent: percent.toFixed(2), | |
completed: mbytes.toFixed(2) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment