Downloading file from ajax result using blob

So I solved the problem using AJAX 2. It natively supports binary streams. You can’t use jQuery for that, unless you base64 encode everything, apparently.

Working code looks like this:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/le/url', true);
xhr.responseType="blob";
$.each(SERVER.authorization(), function(k, v) {
    xhr.setRequestHeader(k, v);
});
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function(e) {
    preloader.modal('hide');
    if (this.status == 200) {
        var blob = new Blob([this.response], {type: 'application/vnd.ms-excel'});
        var downloadUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "data.xls";
        document.body.appendChild(a);
        a.click();
    } else {
        alert('Unable to download excel.')
    }
};
xhr.send(JSON.stringify(jsonData));

Hope this helps.

Leave a Comment