文件在javascript / Extjs中下载一个字节数组作为文件 [英] File download a byte array as a file in javascript / Extjs

查看:100
本文介绍了文件在javascript / Extjs中下载一个字节数组作为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Ext Js解决方案中,我正在调用一个返回此JSON格式的服务

In my Ext Js solution I am calling a service which is returning this JSON format

{"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)

到目前为止好

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

But the file I get is corrupted so I suspect I need to Encode/Decode the file variable?

推荐答案

我必须先将文件转换为Uint8Array,然后再将其传递给Blob

I had to convert the file into a Uint8Array before passing it to the 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

Reading this answer helped a lot https://stackoverflow.com/a/16245768/1016439

这篇关于文件在javascript / Extjs中下载一个字节数组作为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆