jQuery: implementare un sistema di upload dei file in AJAX

Con jQuery possiamo implementare un sistema di upload dei file in AJAX.

jQuery di Gabriele Romanato

Con jQuery possiamo implementare un sistema di upload dei file in AJAX.

Dato il seguente form HTML:


<form action="" id="upload" method="post" enctype="multipart/form-data">
  <div>
      <input type="file" id="file" name="file">
      <input type="submit" value="Upload">
  </div>
</form>

Il codice jQuery รจ il seguente:


$( "#upload" ).on( "submit", function( e ) {
    e.preventDefault();
    var file = $( "#file" )[0].files[0];
    var formData = new FormData();
    formData.append( "file", file );

    $.ajax({
        url: "/upload",
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function( response ) {
            if( response.code === "OK" ) {
                //...
            }
        }
    });
});

Commenti