Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
417 views
Welcome To Ask or Share your Answers For Others

1 Answer

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...