![](/img/trans.png)
[英]Why is 'xlsx' used with 'file-saver' to download excel?
[英]xlsx file corrupted while downloading with the file-saver npm package
我在下载xlsx
文件时遇到问题。 我的 excel 文件是用js-xlsx生成的。 我必须添加一些授权标头来验证服务器上的传入请求。 因此,我不能简单地从客户端在新窗口中打开链接。 出于测试目的,我尝试通过直接点击我的 API 端点的浏览器链接来下载文件(当然是通过临时删除授权中间件)。 浏览器下载文件没有任何问题或损坏。 不幸的是,通过axios get 请求使用filesaver.js时,客户端下载功能并非如此。
我发送响应的后端代码片段是:
//..... Some code for writing the workBook
const workBookOutput = xlsx.write(workBook, {
bookType: 'xlsx',
type: 'buffer'
});
const xlsxFileBuffer = Buffer.from(workBookOutput);
// res is express HTTP response object
res.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.set('Content-Disposition', 'attachment; filename=excel-export.xlsx');
res.status(200).send(xlsxFileBuffer);
我的客户端代码的一部分是:
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
// here I add some real jwt token in my code, not the dummy that I have below
headers.authorization = `bearer asklndashduwkhd2oo832uejh32oihjdoasincas`;
const options = {
'get',
'https://myURLToAPi/api',
headers,
responseType: 'arraybuffer'
}
const response = await axios(options);
//fileSaver is required above in file
fileSaver.saveAs(
new Blob([response.data], {
type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}),
'excel.xlsx'
);
我仍然只得到损坏的文件。 我在服务器端和客户端都尝试了多个选项,但是,下载的文件总是损坏。 在获得我的workbookOutput
后,我尝试不制作另一个Buffer.from
仍然没有任何变化。 有人可以在这方面帮助我吗? 我错过了什么吗?
这是我尝试打开下载损坏后得到的图片。
我有一个类似的问题 - 我在 Django 中生成 Excel,获取字节然后使用 Axios 查询它。 使用 FileSaver 生成的 Excel 已损坏,并且就像 @Seeker 提到的那样,它的大小是原来的两倍。
但是,在 Postman 中进行测试时,我可以获得一个普通文件。 什么解决了我的问题是设置
responseType: 'blob'
在 axios 选项中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.