简体   繁体   English

如何将FormData附加到XMLHttpRequest

[英]How to attach FormData to an XMLHttpRequest

I have a jquery request like this 我有一个这样的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) {
            }
        });
    }

which works fine for uploading an image and sending it to server. 可以很好地用于上传图像并将其发送到服务器。 But it does not handle binary return types (for receiving images in binary format). 但是它不处理二进制返回类型(用于接收二进制格式的图像)。

Then I have this other code here 然后我在这里有其他代码

    // 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();
    };

which handles the specification I need. 可以处理我需要的规范。 But the problem is, how do I modify this working code so that I can attach a FormData() object with an image? 但是问题是,如何修改此工作代码,以便可以将FormData()对象与图像相连?

Thanks 谢谢

You can attach it as below: 您可以按如下所示进行附加:

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 资源

The modification the code needs it to change the request type to POST and pass the FormData object to the send method 修改代码需要它将请求类型更改为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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM