本文介绍了通过Javascript将二进制数据下载为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对返回二进制数据的API进行ajax调用。我想知道是否有可能采取这种二进制数据并在新窗口中显示给客户端?这就是我现在正在做的事情。问题是,文档打开了,但它完全空白。

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?

推荐答案

好的,我明白了。我必须指定responseType为'数组缓冲区':

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

这篇关于通过Javascript将二进制数据下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-01 10:56