Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
}

jsfiddle

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

like image 874
Cornwell Avatar asked Jan 09 '14 18:01

Cornwell


1 Answers

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.

Here is an example :

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);

(Use the same showData function)

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.

Hope it helped

like image 122
DARK_DUCK Avatar answered Oct 26 '22 17:10

DARK_DUCK