'how to calculate upload speed in js
i'm working on a django website and i have a view where the user is able to upload videos and i need to add a button for the user so he can make a short test for his upload speed after a lot of research i found this script but it seems that it's not working and i could not know why
var http = new XMLHttpRequest();
var startTime, endTime;
var myData = "d="; // the raw data you will send
for(var i = 0 ; i < 1022 ; i++) //if you want to send 1 kb (2 + 1022 bytes = 1024b = 1kb). change it the way you want
{
myData += "k"; // add one byte of data;
}
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", myData .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
endTime = (new Date()).getTime();
ShowData();
}
}
startTime = (new Date()).getTime();
http.send(myData);
function ShowData()
{
var duration = (endTime - startTime) / 1000;
var bitsLoaded = myData * 8;
var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2);
alert("Speed: " + speedMbps + " Mbps");
}
so is there any simple method for calculating the upload speed of the user or any fix for this script
Solution 1:[1]
You can use the progress event of the upload property
http.upload.addEventListener('progress', function(e){
console.log(e.loaded + ' uploaded out of ' + e.total);
// do your calculations here
}, false);
Solution 2:[2]
Old post but saw no solution and I was wanting to calculate upload speeds as well. Here is my solution.
var timestamp = new Date().getTime();
var chunk = 0;
http.upload.addEventListener('progress', function(e){
if (elengthComputable){
// bytes transferred since last update
bytes = e.loaded - chunk;
chunk = e.loaded;
// Get number of seconds since last update
ms = new Date().getTime();
elapsed = (ms - timestamp) / 1000.0
timestamp = ms;
// Divide by elapsed time to get bytes per second
bps = bytes / elapsed;
// Output upload speed
console.log("Speed: " + formatBytes(bps)+"/s");
}
}, false);
The formatBytes() function I use is provided on this page: Correct way to convert size in bytes to KB, MB, GB in JavaScript
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Musa |
| Solution 2 | Phaelax z |
