且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery相当于XMLHttpRequest的上传?

更新时间:2022-06-23 05:33:02

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

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);