簡體   English   中英

如何將FormData附加到XMLHttpRequest

[英]How to attach FormData to an XMLHttpRequest

我有一個這樣的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()對象與圖像相連?

謝謝

您可以按如下所示進行附加:

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.
}

資源

修改代碼需要它將請求類型更改為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