获取剩余时间并上传文件速度 - ajax jquery / js

时间:2015-03-06 06:00:38

标签: javascript jquery ajax

jQuery.ajax
({
    url: ajaxurl,
    type: "POST",
    xhr: function()
    {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener( 'progress', function( e )
        {
            if( e.lengthComputable )
            {
                // Append progress percentage.
                var loaded = e.loaded;
                var total = e.total;
                var progressValue = Math.round( ( loaded / total ) * 100 );

                // Bytes received.
                jQuery( '.recievedValue' ).html( '' );
                jQuery( '.recievedValue' ).append( formatFileSize( loaded ) + ' / ' );

                // Total bytes.
                jQuery( '.totalValue' ).html( '' );
                jQuery( '.totalValue' ).append( formatFileSize( total ) );

                // Percentage.
                progressElement.find( 'input' ).val( progressValue ).change();
            }
        }, false );
        return xhr;
    },
    success: function( data )
    {}
});

这是我的ajax功能。我可以得到加载的字节,总字节数和百分比值。但我还需要获得剩余时间并以(kb / sec)上传文件速度。有什么方法可以得到这两个值。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:9)

尝试这样的事情,它应该让你朝着正确的方向前进:

jQuery.ajax
({
    url: ajaxurl,
    type: "POST",
    xhr: function()
    {
        var xhr = new window.XMLHttpRequest();
        var started_at = new Date();
        xhr.upload.addEventListener( 'progress', function( e )
        {
            if( e.lengthComputable )
            {
                // Append progress percentage.
                var loaded = e.loaded;
                var total = e.total;
                var progressValue = Math.round( ( loaded / total ) * 100 );

                // Bytes received.
                jQuery( '.recievedValue' ).html( '' );
                jQuery( '.recievedValue' ).append( formatFileSize( loaded ) + ' / ' );

                // Total bytes.
                jQuery( '.totalValue' ).html( '' );
                jQuery( '.totalValue' ).append( formatFileSize( total ) );

                // Time Remaining
                var seconds_elapsed =   ( new Date().getTime() - started_at.getTime() )/1000;
                var bytes_per_second =  seconds_elapsed ? loaded / seconds_elapsed : 0 ;
                var Kbytes_per_second = bytes_per_second / 1000 ;
                var remaining_bytes =   total - loaded;
                var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;
                jQuery( '.timeRemaining' ).html( '' );
                jQuery( '.timeRemaining' ).append( seconds_remaining );

                // Percentage.
                progressElement.find( 'input' ).val( progressValue ).change();
            }
        }, false );
        return xhr;
    },
    success: function( data )
    {}
});