Javascript 文件下载一个字节数组作为javascript / Extjs中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27946228/
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
File download a byte array as a file in javascript / Extjs
提问by Jepzen
In my Ext Js solution I am calling a service which is returning this JSON format
在我的 Ext Js 解决方案中,我正在调用一个返回此 JSON 格式的服务
{"success":true,"filename":"spreadsheet.xlsx","file":[80,75,3,4,20,0,...(many more)]}
How can I make a file download dialog with the filename and the content of the byte array (file) ?
如何使用文件名和字节数组(文件)的内容制作文件下载对话框?
UPDATE
更新
So I found this bit to start the downlaod
所以我找到了这个开始下载
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)
So far good
到目前为止还好
But the file I get is corrupted so I suspect I need to Encode/Decode the file variable?
但是我得到的文件已损坏,所以我怀疑我需要对文件变量进行编码/解码?
回答by Jepzen
I had to convert the file into a Uint8Array before passing it to the Blob
在将文件传递给 Blob 之前,我必须将文件转换为 Uint8Array
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)
Reading this answer helped a lot https://stackoverflow.com/a/16245768/1016439
阅读这个答案有很大帮助https://stackoverflow.com/a/16245768/1016439
回答by scoDubblT
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
基于 Jepzen 的响应,我能够使用这种技术从浏览器中的 AWS S3 下载文档。+1 杰普森
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);
}
});

