繁体   English   中英

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

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

我正在通过ajax / jquery上传文件。 演示可以在这里找到。 此函数将输出完成百分比:

   //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%
            }
    }

但是如何获得传输速度?

当我打印OnProgress的所有变量时,我有以下内容:

事件: [OBJECT XMLHTTPREQUESTPROGRESSEVENT]

位置: 25668

合计: 2122576

完成百分比: 2

我试图输出event.speed但我不确定。

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

您可以估计它在客户端...

最简单的方法是在JavaScript中添加全局变量,以确保上传开始时间。

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

并在html中

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

那么您将需要添加以下内容:

//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%
        }
}

现在,您只需要使用位置 /时间来计算从现在开始的平均速度。

暂无
暂无

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

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