计算上传速度 [英] Calculate upload speed
问题描述
使用此代码,我可以计算下载速度:
Using this code I'm able to calculate my download speed:
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请求的旁边脚本来计算上传速度
How would I send that same image back to a dummy php (not sure if it would be required to exist a server-side script to "accept" the POST request) in my server to calculate the upload speed
推荐答案
如果你想测试上传速度我不明白你为什么要发送这个特定的图像。
If you want to test the upload speed I don't see why you would want to send this specific image.
我宁愿发送原始数据。
I would rather send raw data.
以下是一个例子:
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函数)
(Use the same showData function)
您也可以多次发送图像数据而不是字母k,但需要更多代码,我不会看到任何改进。
You could also send the data of the image instead of the letter "k" multiple times but it would need more code and I won't see any improvements doing this.
希望它有所帮助
这篇关于计算上传速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!