使用 Javascript 下载二进制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17696516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download Binary Files with Javascript
提问by nuno.filipesf
I want to download binary files using Javascript.
我想使用 Javascript 下载二进制文件。
I have a REST service that returns the binary data and i want to know if its possible to show the binary file, whichever the file extension.
我有一个返回二进制数据的 REST 服务,我想知道是否可以显示二进制文件,无论文件扩展名是什么。
This is my current code:
这是我当前的代码:
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);
Thanks!
谢谢!
回答by Jo David
Have a look at the MDN article on XMLHttpRequest.
查看关于XMLHttpRequest的 MDN 文章。
If you set the response of the XMLHttpRequest to ArrayBufferyou could do the following:
如果您将 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();
Option 2:
You could use Blobas the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)
选项 2:
您可以使用Blob作为 XMLHttpRequest 的响应。然后也许将它保存在 FileSystem ( FileSystem API)
It may look like:
它可能看起来像:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
onDownloaded(this);
};
xhr.send();
Option 3:
If you only want to download and "show" images you can easily do this like so:
选项 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