最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calculate upload speed - Stack Overflow

programmeradmin6浏览0评论

Using this code I'm able to calculate my download speed:

var imgAddr = ".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

Using this code I'm able to calculate my download speed:

var imgAddr = "http://upload.wikimedia/wikipedia/mons/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

Share Improve this question edited Jan 9, 2014 at 18:20 Cornwell asked Jan 9, 2014 at 18:08 CornwellCornwell 3,4108 gold badges54 silver badges85 bronze badges 5
  • What are you trying to do with the image? why did you make a script to calculate the download speed? – imbask Commented Jan 9, 2014 at 18:18
  • why?... because I wanted to show the user his bandwidth speed. I can show the download speed with a certain accuracy, now I want to get the upload speed. – Cornwell Commented Jan 9, 2014 at 18:22
  • 2 it seems easier if you just send him to a speed test website – Huangism Commented Jan 9, 2014 at 18:22
  • @Huangism: I am also using an API from a speedtest website. But I need to know their speed to the server – Cornwell Commented Jan 9, 2014 at 18:36
  • @Cornwell Can you please explain why you used "?n=" + Math.random(); at the end of image url? And I do not know what is var download_size = 5*1024*1024; use for? – Mahdi Commented Aug 5, 2021 at 4:12
Add a ment  | 

3 Answers 3

Reset to default 7

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

For ajax uploads:

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);
var xhr = new window.XMLHttpRequest();  
let now;
let lastNow = new Date().getTime()/1000;
let elapsed;
let lastLoadBytes = 0;
let speedTest = 0;
let lastSpeedTest = 0;
xhr.upload.addEventListener("progress", function(evt) {
    
    if (evt.lengthComputable) {
        var percentComplete = Math.round((evt.loaded / evt.total) * 100);
    
        now = new Date().getTime()/1000;
        lastLoadBytes = evt.loaded - lastLoadBytes;                                         
        elapsed = (now - lastNow); //
        lastNow = now;          
        speedTest = Math.round(((lastLoadBytes)/elapsed)/1024/1024);    
        speedTest = Math.round((speedTest+lastSpeedTest)/2);
            
        $("#speed").html('<span>'+speedTest+' MB/s</span>');
        $("#prog").html('<div class="progress"><div class="progress-bar bg-success" role="progressbar" style="width: '+percentComplete+'%" aria-valuenow="'+percentComplete+'" aria-valuemin="0" aria-valuemax="100">'+percentComplete+'% </div></div>');
        
        lastLoadBytes = evt.loaded;
        lastSpeedTest = speedTest;
    }}
发布评论

评论列表(0)

  1. 暂无评论