在我的Ext Js解决方案中,我正在调用一个返回此JSON格式的服务
{"success":true,"filename":"spreadsheet.xlsx","file":[80,75,3,4,20,0,...(many more)]}
如何使用文件名和字节数组(文件)的内容创建文件下载对话框?
更新
所以我发现这一点开始下载
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob(data.file, { type: 'application/octet-stream' }));
a.download = data.filename;
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
到目前为止很好
但我得到的文件已损坏,所以我怀疑我需要对文件变量进行编码/解码?
答案 0 :(得分:25)
我必须先将文件转换为Uint8Array,然后再将其传递给Blob
var arr = data.file;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
a.download = data.filename;
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
阅读这个答案有很多帮助https://stackoverflow.com/a/16245768/1016439
答案 1 :(得分:0)
Building on Jepzen's response, I was able to use this technique to download a document from AWS S3 from within the browser. +1 Jepzen
s3.getObject(params, function(err, data) {
if (err === null) {
var arr = data.Body;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: 'application/octet-stream' }));
a.download = fName; //fName was the file name portion of the key what was passed in as part of the key value within params.
// Append anchor to body.
document.body.appendChild(a)
a.click();
// Remove anchor from body
document.body.removeChild(a)
} else {
result = 'failure'
console.log("Failed to retrieve an object: " + err);
}
});