我在下载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'
);
我仍然只得到损坏的文件。我在服务器端和客户端都尝试了多个选项,但是,下载的文件总是损坏。Buffer.from
在得到我的workbookOutput
仍然没有改变之后,我尝试不做另一个。有人可以在这方面帮助我吗?我错过了什么吗?
如果我尝试打开它,这是我得到的损坏下载的图片。