简体   繁体   English

通过Javascript将二进制数据下载为文件

[英]Download Binary Data as a File Via Javascript

I'm making an ajax call to an API that returns binary data. 我正在对一个返回二进制数据的API进行ajax调用。 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? 有任何想法吗?

Okay, I figured it out. 好的,我明白了。 I had to specify the responseType as 'array buffer': 我必须将responseType指定为'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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM