使用Javascript下载二进制文件

nun*_*esf 21 javascript

我想使用Javascript下载二进制文件.

我有一个REST服务,它返回二进制数据,我想知道它是否可以显示二进制文件,无论文件扩展名如何.

这是我目前的代码:

var xhr = new XMLHttpRequest;
xhr.open("GET", requestUrl);
xhr.addEventListener("load", function () {
    var ret = [];
    var len = this.responseText.length;
    var byte;
    for (var i = 0; i < len; i++) {
        byte = (this.responseText.charCodeAt(i) & 0xFF) >>> 0;
        ret.push(String.fromCharCode(byte));
    }
    var data = ret.join('');
    data = "data:application/pdf;base64," + btoa(data);

    window.open(data, '_blank', 'resizable, width=1020,height=600');
}, false);

xhr.setRequestHeader("Authorization", "Bearer " + client.accessToken);
xhr.overrideMimeType("octet-stream; charset=x-user-defined;");
xhr.send(null);
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jo *_*vid 44

看看关于XMLHttpRequest的MDN文章.

如果将XMLHttpRequest的响应设置为ArrayBuffer,则可以执行以下操作:

var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "arraybuffer";

xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response], {type: "application/pdf"});
        var objectUrl = URL.createObjectURL(blob);
        window.open(objectUrl);
    }
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)

选项2:
您可以使用Blob作为XMLHttpRequest的响应.然后可能将其保存在FileSystem(FileSystem API)中

它可能看起来像:

var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";

xhr.onload = function () {
    onDownloaded(this);
};
xhr.send();
Run Code Online (Sandbox Code Playgroud)

选项3:
如果您只想下载并"显示"图像,您可以轻松地执行此操作:

var img = new Image();

// add the onload event before setting the src
img.onload = function() {
    onImageDownloaded(img);
}

// start the download by setting the src property
img.src = requestUrl
Run Code Online (Sandbox Code Playgroud)

  • 为什么你不使用内容类型标题而不是硬编码类型作为应用程序/pdf? (2认同)
  • 函数“onDownloaded”在哪里定义? (2认同)