使用此代码我可以计算下载速度:
var imgAddr = "http://upload.wikimedia.org/wikipedia/commons/2/2d/Snake_River_%285mb%29.jpg" + "?n=" + Math.random();
var startTime, endTime;
var download_size = 5*1024*1024;
var img = new Image();
img.onload = function () {
endTime = (new Date()).getTime();
ShowData();
}
startTime = (new Date()).getTime();
img.src = imgAddr;
function ShowData()
{
var duration = (endTime - startTime) / 1000;
var bitsLoaded = download_size * 8;
var speedMbps = ((bitsLoaded / duration) / 1024 / 1024).toFixed(2);
alert("Speed: " + speedMbps + " Mbps");
}
如何将同一图像发送回虚拟php(不确定是否需要在我的服务器中存在服务器端脚本以“接受”POST请求)来计算上传>强>速度
答案 0 :(得分:4)
如果您想测试上传速度,我不明白为什么您要发送此特定图片。
我宁愿发送原始数据。
以下是一个例子:
var http = new XMLHttpRequest();
var startTime, endTime;
var url = "script_that_whill_handle_post.php";
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);
(使用相同的showData函数)
你也可以发送图像的数据而不是字母&#34; k&#34;多次,但它需要更多的代码,我没有看到任何改进这样做。
希望有所帮助
答案 1 :(得分:3)
对于ajax上传:
var lastNow = new Date().getTime();
var lastKBytes = 0;
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var now = new Date().getTime();
var bytes = e.loaded;
var total = e.total;
var percent = bytes / total * 100;
var kbytes = bytes / 1024;
var mbytes = kbytes / 1024;
var uploadedkBytes = kbytes - lastKBytes;
var elapsed = (now - lastNow) / 1000;
var kbps = elapsed ? uploadedkBytes / elapsed : 0 ;
lastKBytes = kbytes;
lastNow = now;
console.log(mbytes.toFixed(2) + "MB (" + percent.toFixed(2) + "%) " + kbps.toFixed(2) + "KB/s");
}
}, false);