【问题标题】:File download a byte array as a file in javascript / Extjs文件将字节数组下载为javascript / Extjs中的文件
【发布时间】:2015-03-12 19:56:11
【问题描述】:

在我的 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)

目前还不错

但我得到的文件已损坏,所以我怀疑我需要对文件变量进行编码/解码?

【问题讨论】:

标签: javascript extjs3


【解决方案1】:

在将文件传递给 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)

阅读这个答案很有帮助https://stackoverflow.com/a/16245768/1016439

【讨论】:

【解决方案2】:

基于 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);
      }
});
   

【讨论】:

    猜你喜欢
    • 2016-05-04
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 2017-06-04
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多