【问题标题】:How to attach FormData to an XMLHttpRequest如何将 FormData 附加到 XMLHttpRequest
【发布时间】:2015-11-12 05:30:00
【问题描述】:

我有一个这样的 jquery 请求

    function sendData() {

        var formData = new FormData($("#myform")[0]);
        $.ajax({
            type: 'POST',
            url: "/process",
            data: formData,
            dataType: 'json',
            contentType:false,
            cache:false,
            processData:false,
            timeout: 30 * 1000,
            beforeSend: function( xhr ) {
            },
            success: function(jsonData,status,xhr) {
            },
            error: function(data,status,xhr) {
            }
        });
    }

这适用于上传图像并将其发送到服务器。但它不处理二进制返回类型(用于接收二进制格式的图像)。

然后我这里有其他代码

    // http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
    function fetchBlob(uri, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', uri, true);
        xhr.responseType = 'arraybuffer';

        xhr.onload = function(e) {
            if (this.status == 200) {
                var blob = this.response;
                if (callback) {
                    callback(blob);
                }
            }
        };
        xhr.send();
    };

它处理我需要的规范。但问题是,如何修改这个工作代码,以便可以将 FormData() 对象与图像附加在一起?

谢谢

【问题讨论】:

标签: javascript jquery binary


【解决方案1】:

您可以按如下方式附加:

function fetchBlob(uri, callback) {
    var formData = new FormData($("#myform")[0]); 
    var xhr = new XMLHttpRequest();
    xhr.open('GET', uri, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function(e) {
        if (this.status == 200) {
            var blob = this.response;
            if (callback) {
                callback(blob);
            }
        }
    };
    xhr.send(formData); //attach it here.
}

SOURCE

【讨论】:

  • 我试过了,但是node.js无法检测到数据中的图片。
【解决方案2】:

代码需要修改请求类型为POST并将FormData对象传递给send方法

// http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
function fetchBlob(uri, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', uri, true);
    xhr.responseType = 'arraybuffer';
    var formData = new FormData($("#myform")[0]);
    xhr.onload = function(e) {
        if (this.status == 200) {
            var buffer = this.response;
            if (callback) {
                callback(buffer);
            }
        }
    };
    xhr.send(formData);
}

【讨论】:

    猜你喜欢
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2017-12-06
    • 2020-10-19
    • 2017-12-25
    • 2020-06-23
    • 2023-01-06
    相关资源
    最近更新 更多