javascript - Comment puis-je télécharger des fichiers asynchronement avec jQuery

Mots clés : javascriptjqueryajaxasynchronousxmlhttprequestjavascript

meilleur 3 Réponses javascript - Comment puis-je télécharger des fichiers asynchronement avec jQuery

vote vote

98

<form enctype="multipart/form-data">     <input name="file" type="file" />     <input type="button" value="Upload" /> </form> <progress></progress> 
$(':file').on('change', function () {   var file = this.files[0];    if (file.size > 1024) {     alert('max upload size is 1k');   }    // Also see .name, .type }); 
$(':button').on('click', function () {   $.ajax({     // Your server script to process the upload     url: 'upload.php',     type: 'POST',      // Form data     data: new FormData($('form')[0]),      // Tell jQuery not to process data or worry about content-type     // You *must* include these options!     cache: false,     contentType: false,     processData: false,      // Custom XMLHttpRequest     xhr: function () {       var myXhr = $.ajaxSettings.xhr();       if (myXhr.upload) {         // For handling the progress of the upload         myXhr.upload.addEventListener('progress', function (e) {           if (e.lengthComputable) {             $('progress').attr({               value: e.loaded,               max: e.total,             });           }         }, false);       }       return myXhr;     }   }); }); 
vote vote

82

$(document).ready(function() {   $("#uploadbutton").jsupload({     action: "addFile.do",     onComplete: function(response){       alert( "server response: " + response);     }   }); }); 
vote vote

72

$.ajax({   url: 'file/destination.html',    type: 'POST',   data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.   processData: false,   contentType: false                    // Using FormData, no need to process data. }).done(function(){   console.log("Success: Files sent!"); }).fail(function(){   console.log("An error occurred, the files couldn't be sent!"); }); 
$.ajax({   url: 'file/destination.html',    type: 'POST',   // Set the transport to use (iframe means to use Bifröst)   // and the expected data type (json in this case).   dataType: 'iframe json',                                   fileInputs: $('input[type="file"]'),  // The file inputs containing the files to send.   data: { msg: 'Some extra data you might need.'} }).done(function(){   console.log("Success: Files sent!"); }).fail(function(){   console.log("An error occurred, the files couldn't be sent!"); }); 

Questions similaires