0

I have a jquery request like this

    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?

Thanks

sneaky
  • 2,141
  • 9
  • 31
  • 38

2 Answers2

1

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

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

The modification the code needs it to change the request type to POST and pass the FormData object to the send method

// 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);
}
Musa
  • 96,336
  • 17
  • 118
  • 137