[英]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我在一个 django 网站上工作,我有一个视图,用户可以上传视频,我需要为用户添加一个按钮,这样他就可以在经过大量研究后对他的上传速度做一个简短的测试我发现了这个脚本,但它似乎不起作用,我不知道为什么
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那么是否有任何简单的方法来计算用户的上传速度或对此脚本的任何修复
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.