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.
Just a clarification, this is a function available on
XMLHttpRequest
Level 2.– bfavaretto
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
– Giovanne Afonso
@Giovanneafonso Both forms are correct. The attribute
upload
is aXMLHttpRequestUpload
implementingEventTarget
that has the methodaddEventListener
. The very oneXMLHttpRequest
also implementsEventTarget
, probably delegating the assignment of the listener to its attributeupload
.– mgibsonbr
In my case, when I linked the event directly to xhr, it was called ONCE after the upload with
event.loaded = [um número]
andevent.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.– Giovanne Afonso