jQuery相当于XMLHttpRequest的上传?

met*_*ras 10 javascript ajax upload jquery

使用HTML5的File API,上传是通过uploadXMLHttpRequest.中调用的对象进行的.是我正在使用的教程(以及Google缓存镜像,因为它现在已经关闭).这是相关部分:

// Uploading - for Firefox, Google Chrome and Safari
xhr = new XMLHttpRequest();

// Update progress bar
xhr.upload.addEventListener("progress", function (evt) {
Run Code Online (Sandbox Code Playgroud)

如您所见,为了跟踪上传进度,该XMLHttpRequest对象有一个名为的属性upload,我们可以添加一个事件处理程序.

我的问题是:jQuery是一个等价的吗?.我试图让代码尽可能干净,并且尽可能地跨浏览器兼容,因为每当微软认为这是一个好主意时(尽管听起来会像2012年或2013年那样).

Lou*_*eau 17

以下是我想出来解决这个问题的方法.$ .ajax()调用允许提供回调以生成XHR.我只是在调用请求之前生成一个,设置它然后创建一个闭包以在$ .ajax()需要它时返回它.如果他们只是通过jqxhr访问它会更容易,但他们没有.

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);
Run Code Online (Sandbox Code Playgroud)