jQuery equivalent to XMLHttpRequest's upload? jQuery equivalent to XMLHttpRequest's upload? ajax ajax

jQuery equivalent to XMLHttpRequest's upload?


Here is what I came up with to get around the issue. The $.ajax() call allows to provide a callback to generate the XHR. I just generate one before calling the request, set it up and then create a closure to return it when $.ajax() will need it. It would have been much easier if they just gave access to it through jqxhr, but they don't.

var reader = new FileReader();reader.onloadend = function (e) {    var xhr, provider;    xhr = jQuery.ajaxSettings.xhr();    if (xhr.upload) {        xhr.upload.addEventListener('progress', function (e) {            // ...        }, false);    }       provider = function () {        return xhr;    };      // Leave only the actual base64 component of the 'URL'    // Sending as binary ends up mangling the data somehow    // base64_decode() on the PHP side will return the valid file.    var data = e.target.result;    data = data.substr(data.indexOf('base64') + 7);     $.ajax({        type: 'POST',        url: 'http://example.com/upload.php',        xhr: provider,        dataType: 'json',        success: function (data) {            // ...        },          error: function () {            // ...        },          data: {            name: file.name,            size: file.size,            type: file.type,            data: data,        }       }); };  reader.readAsDataURL(file);


The documentation for the jqXHR (the superset of the XMLHttpRequest that is returned from jQuery's .ajax() call) does not describe the update feature as being exposed, which does not mean it isn't exposed. This question, though, seems to indicate that upload is not exposed. The answer provides a way to get to the native XMLHttpRequest object.

In versions before jQuery 1.5 the XMLHttpRequest object was exposed directly, and so you can access any feature of it that the browser supports. This tutorial for building a drag and drop uploader does just that.

A search for jquery html 5 file upload brings up this plugin to do multiple file upload using the HTML 5 file API, but this plugin does not currently work in IE. If you don't want to use HTML 5 and instead do want to have support cross-browser now, there are other plugins you can look into for jQuery on the jQuery plugin site.