jQuery: upload dei file con HTML5 e AJAX

Short link

Con jQuery possiamo sfruttare le feature più recenti di HTML5 e AJAX per l'upload dei file.

La soluzione è la seguente:


(function( $ ) {
  $.fn.html5Upload = function( options ) {
      options = $.extend({
        file: "#file",
        url: "/upload",
        progress: $.noop,
        complete: $.noop,
        error: $.noop,
        abort: $.noop
      }, options);

      return this.each(function() {
        var $form = $( this );
        if( $form.attr( "enctype" ) !== "multipart/form-data" ) {
           throw new Error( "Invalid form data type" );
        }  
        $form.on( "submit", function( e ) {
            e.preventDefault();
            var file = $form.find( options.file ).get( 0 );
            
            var formdata = new FormData();
            formdata.append( $form.find( options.file ).attr( "name" ), file );

            var ajax = new XMLHttpRequest();

            ajax.upload.addEventListener( "progress", options.progress, false );
          	ajax.addEventListener( "load", options.complete, false );
          	ajax.addEventListener( "error", options.error, false );
          	ajax.addEventListener( "abort", options.abort, false );
          	ajax.open( "POST", options.url );
          	ajax.send( formdata );
        });
      });
  };
})( jQuery );

Esempio d'uso:


$( "#form" ).html5Upload({
    progress: function( event ) {
        var percent = ( event.loaded / event.total ) * 100;
        $( "#progress-bar" ).css( "width", Math.round( percent ) + "%" );
    }
});