How to get the value of the current percentage of an upload?

Asked

Viewed 4,056 times

29

I’m working with PHP, but I imagine it can be done only with javascript/jQuery. When I upload the browser shows the percentage in the status bar. I would like to take this value and create from it a custom progress bar.

The bar I know how to do. I just don’t know how to get the current percentage value. How to get it?

3 answers

22

In HTML5 it is possible to do this by adding a listener progress to the property upload of a XMLHttpRequest (used to upload the file via Ajax):

xhr.upload.addEventListener("progress", function(e) {
    var pc = parseInt(100 - (e.loaded / e.total * 100));
    // Atualizar sua barra de progresso usando "pc"
}, false);

Source (and full example) in English: How to Create Graphical File Upload Progress Bars in HTML5 and Javascript. This functionality, it seems, is supported by all popular browsers, in its most current version only (that is, it does not work in older versions but still widely used, such as IE9 or earlier).

  • 1

    Just a clarification, this is a function available on XMLHttpRequest Level 2.

  • 1

    Your answer worked for me, but yesterday I spent the whole day searching and nowhere had I seen that the event is to be applied to the "upload" property of xhr. Even on MDN it is documented that the progress event should be in xhr itself. See on MDN

  • 1

    @Giovanneafonso Both forms are correct. The attribute upload is a XMLHttpRequestUpload implementing EventTarget that has the method addEventListener. The very one XMLHttpRequest also implements EventTarget, probably delegating the assignment of the listener to its attribute upload.

  • 1

    In my case, when I linked the event directly to xhr, it was called ONCE after the upload with event.loaded = [um número] and event.total = 0. Switching to xhr.upload worked, the script is pretty simple, maybe it’s some configuration on the server, but anyway, I’m glad it’s working now.

12


Using the ajaxform jquery plugin to do so:

 $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });

Download the plugin here http://jquery.malsup.com/form/#Getting-Started

Without the plugin is kind of complicated I strongly recommend downloading it as it is very useful to submit Forms via ajax among other things.

7

As already mentioned, there are javascript libraries that make the job difficult for you. In general it is not worth going into low level details as probably different versions of different browsers will be used you will have to deal with numerous compatibility issues.

Javascript libraries

I recommend using the plugin jQuery File Upload. I’ve used it in some projects, including supporting multiple simultaneous uploads showing the results in a table. See demo here.

Another alternative, mainly to support older browsers, is the uploadify. He owns a fallback using Flash, so when the browser does not support advanced upload features, it will use this alternative automatically.

Implementation that depends on PHP

On the other hand, if this functionality is important to your application and it will receive large uploads, you can use the recent functionality Session Upload Progress PHP, available as of version 5.4.

The Session Upload Progress does not affect the upload request, but allows you to monitor the upload through a variable placed in the session. Then you could do an Ajax from the page to recover the percentage of the upload by passing the field name by parameter. See the example:

<?php
//nome do elemento da sessão contendo um array de informações de upload
$key = ini_get("session.upload_progress.prefix") .
        $_POST[ini_get("session.upload_progress.name")];

//recuperao vetor com informações de upload
$uploads_array = $_SESSION[$key];

//exibe as informações de um upload em específico
var_dump($uploads_array[$_POST["myField"]]);
?>

To enable functionality, enable the parameter session.upload_progress.enabled in the php.ini.

See the documentation for more details.

  • 1

    +1 for mentioning the jQuery File Upload of blueimp, already worked with the plugin and is very cool.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.