8

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.

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

        // Append the binary data to the blob
        bb.append(xhr.responseText);

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

Any ideas?

3
  • Are you using HTTPS with IE? If so, see stackoverflow.com/questions/773308/… Commented Mar 8, 2012 at 15:50
  • Its a chrome extension, so I don't have to worry about IE. Commented Mar 8, 2012 at 16:09
  • do you have control of the server side implementation? Commented Mar 8, 2012 at 16:41

1 Answer 1

9

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

function downloadPDF() {

    var xhr = new XMLHttpRequest();
    xhr.open('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);

            window.open(blobURL);
        }
    };

    xhr.send(createRequest());
}
Sign up to request clarification or add additional context in comments.

5 Comments

How do you change the downloaded file name using this method?
using FileSaver will make this easier stackoverflow.com/questions/15211742/…
I am gettign this error when included xhr.responseType ERROR DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). at XMLHttpRequest.x.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (http://localhost:4200/main.js:11702:31)
what's the createRequest() for?
after removing createRequest(), getting this error: Uncaught TypeError: window.WebKitBlobBuilder is not a constructor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.