我正在通过 ajax/jquery 上传文件。可以找到演示here .此函数将输出完成百分比:
//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 的所有变量时,我有这个:
event: [OBJECT XMLHTTPREQUESTPROGRESSEVENT]
position: 25668
total: 2122576
percentComplete: 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%
}
}
现在你只需要使用位置/timespent 来计算从开始到现在的平均速度..
关于javascript - 通过 jquery/Ajax 获取文件上传的传输速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28942902/