我在下载xlsx文件时遇到问题。我的excel文件是用js-xlsx生成的。我必须添加一些authorization headers来验证服务器上的传入请求。出于这个原因,我不能简单地从我的客户端在新窗口中打开链接。出于测试目的,我尝试通过直接点击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,但仍然没有任何变化。有人能在这方面帮助我吗?我是不是遗漏了什么?
这是我尝试打开损坏的下载时所得到的图片。

发布于 2020-05-28 18:31:24
我遇到了类似的问题-我在Django中生成Excel,获取字节,然后使用Axios查询它。用FileSaver生成的Excel被破坏了,就像@Seeker提到的那样,它的大小是原来的两倍。
然而,在Postman中测试时,我可以得到一个普通的文件。解决我的问题的是设置
responseType: 'blob'在axios选项中。
https://stackoverflow.com/questions/57513850
复制相似问题