简体   繁体   中英

Get transfer speed of a file uploading though jquery/Ajax?

I am uploading a file through ajax/jquery. The demo can be found here . This function will output the percentage complete:

   //progress bar function
    function OnProgress(event, position, total, percentComplete)
    {
        //Progress bar
        $('#progressbox').show();
        $('#progressbar').width(percentComplete + '%') //update progressbar percent complete
        $('#statustxt').html(percentComplete + '%'); //update status text
        if(percentComplete>50)
            {
                $('#statustxt').css('color','#000'); //change status text to white after 50%
            }
    }

But how do I get the transfer speed?

When I printed all the variables of OnProgress, I had this:

event: [OBJECT XMLHTTPREQUESTPROGRESSEVENT]

position: 25668

total: 2122576

percentComplete: 2

I have tried to output event.speed but I got undefined.

I do not want calculate the transfer speed on the server-side, and use another ajax request polling simultaneously that returns the amount downloaded, it would not be efficient.

You could estimate it client side...

The easiest way would be to add a global variable in your javascript, for upload start times.

<script language=javascript>
    var starttime = new Date().getTime();
    function setStartTime(){ 
        starttime = new Date().getTime();
    }
</script>

and in the html

<input type="submit" id="submit-btn" value="Upload" style="display: inline-block;" onclick="setStartTime()"/>

then you will need to add some stuff like this:

//progress bar function
function OnProgress(event, position, total, percentComplete)
{
    //Progress bar
    $('#progressbox').show();
    $('#progressbar').width(percentComplete + '%') //update progressbar percent complete
    var timeSpent = new Date().getTime() - starttime ;
    $('#statustxt').html(percentComplete + '% time spent so far:' + String(timeSpent)); //update status text

    if(percentComplete>50)
        {
            $('#statustxt').css('color','#000'); //change status text to white after 50%
        }
}

now you just need to use the position / timespent to calculate the average speed since beginning to now..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM