使用Javascript下载二进制文件 [英] Download Binary Files with Javascript
问题描述
我想使用Javascript下载二进制文件。
I want to download binary files using Javascript.
我有一个REST服务,它返回二进制数据,我想知道它是否可以显示二进制文件,无论文件扩展名如何。
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.
这是我目前的代码:
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);
谢谢!
推荐答案
查看关于 XMLHttpRequest <的MDN文章a>。
Have a look at the MDN article on XMLHttpRequest.
如果将XMLHttpRequest的响应设置为 ArrayBuffer 您可以执行以下操作:
If you set the response of the XMLHttpRequest to ArrayBuffer you could do the following:
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();
选项2:
您可以使用 Blob 作为XMLHttpRequest的响应。然后可以将其保存在FileSystem中( FileSystem API )
Option 2:
You could use Blob as the response of the XMLHttpRequest. And then maybe save it in the FileSystem (FileSystem API)
它可能看起来像:
var xhr = new XMLHttpRequest();
xhr.open("GET", requestUrl);
xhr.responseType = "blob";
xhr.onload = function () {
onDownloaded(this);
};
xhr.send();
选项3:
如果你只是想要下载和显示图像,您可以轻松地这样做:
Option 3:
If you only want to download and "show" images you can easily do this like so:
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
这篇关于使用Javascript下载二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!