简体   繁体   English

获取通过jquery / Ajax上传文件的传输速度?

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

I am uploading a file through ajax/jquery. 我正在通过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: 当我打印OnProgress的所有变量时,我有以下内容:

event: [OBJECT XMLHTTPREQUESTPROGRESSEVENT] 事件: [OBJECT XMLHTTPREQUESTPROGRESSEVENT]

position: 25668 位置: 25668

total: 2122576 合计: 2122576

percentComplete: 2 完成百分比: 2

I have tried to output event.speed but I got undefined. 我试图输出event.speed但我不确定。

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. 我不想计算服务器端的传输速度,并同时使用另一个ajax请求轮询来返回下载的数量,这样效率不高。

You could estimate it client side... 您可以估计它在客户端...

The easiest way would be to add a global variable in your javascript, for upload start times. 最简单的方法是在JavaScript中添加全局变量,以确保上传开始时间。

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

and in the html 并在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.. 现在,您只需要使用位置 /时间来计算从现在开始的平均速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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