[英]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.