Download Binary Data as a File Via Javascript

I'm making an ajax call to an API that returns binary data. I'm wondering if its possible to take that binary data and display it for the client in a new window? This is what I'm doing right now. The problem is, the document opens up, but its completely blank.

    type: "POST",
    url: apiURL,
    data: xmlRequest,
    complete: function(xhr, status) {
        var bb = new window.WebKitBlobBuilder();

        // Append the binary data to the blob

        var blobURL = window.webkitURL.createObjectURL(bb.getBlob('application/pdf'));;

Any ideas?



Okay, I figured it out. I had to specify the responseType as 'array buffer':

function downloadPDF() {

    var xhr = new XMLHttpRequest();'POST', API_URL, true);
    xhr.responseType = 'arraybuffer';

    xhr.onload = function(e) {
        if (this.status == 200) {
            var bb = new window.WebKitBlobBuilder();
            bb.append(this.response); // Note: not xhr.responseText

            var blob = bb.getBlob('application/pdf');
            var blobURL = window.webkitURL.createObjectURL(blob);




Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.