XHR Level2 with jQuery to download files

How can I access a raw XHR object from jQuery Ajax? The fact is, the new XMLHttpRequest Level 2 specification provides a sub-property of XHR called upload, but it seems that jQuery does not have it yet. I want to continue using jQuery Ajax, but I do not know how to combine the new functions with the current jQuery library.

+6
source share
2 answers

In newer versions of jQuery, the raw xhr object is wrapped in a jqXhr object, which has no reference to the new xhr loading property and the documentation does not really understand how to do this. The way I found to do this, with some additional settings, to get a successful jquery-ajax-HTML5 file, was:

var formData = new FormData($('#myForm')[0]); $.ajax({ url: 'upload.php', type: 'POST', xhr: function() { myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ myXhr.upload.addEventListener('progress',progressHandlerFunction, false); } return myXhr; }, data: formData, cache: false, contentType: false, processData: false }); 

with $ .ajaxSettings.xhr () I get the original xhr, then check to see if it has a upload property to bind the progress event to control the progress (HTML5?). Other settings allow me to submit a form via jquery ajax as a FormData object.

+15
source

A slight modification to the DannYOs response. I made a jQuery plugin that you can invoke by entering a file to make it simpler. You just pass it your script load, then your success function, and then your progress function.

 $.fn.upload = function(remote,successFn,progressFn) { return this.each(function() { var formData = new FormData(); formData.append($(this).attr("name"), $(this)[0].files[0]); $.ajax({ url: remote, type: 'POST', xhr: function() { myXhr = $.ajaxSettings.xhr(); if(myXhr.upload && progressFn){ myXhr.upload.addEventListener('progress',progressFn, false); } return myXhr; }, data: formData, cache: false, contentType: false, processData: false, complete : function(res) { if(successFn) successFn(res); } }); }); } 

Using

 $(".myFile").upload("upload.php",function(res) { console.log("done",res); },function(progress) { console.log("progress", progress); }); 
+9
source

Source: https://habr.com/ru/post/903412/


All Articles