2

我在下载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仍然没有改变之后,我尝试不做另一个。有人可以在这方面帮助我吗?我错过了什么吗?

如果我尝试打开它,这是我得到的损坏下载的图片。

在此处输入图像描述

4

1 回答 1

0

我有一个类似的问题——我在 Django 中生成 Excel,获取字节然后使用 Axios 查询它。使用 FileSaver 生成的 Excel 已损坏,就像@Seeker 提到的那样,它的大小是原来的两倍。

但是,在 Postman 中进行测试时,我可以获得一个正常的文件。解决我的问题的是设置

responseType: 'blob'

在 axios 选项中。

于 2020-05-28T10:31:24.340 回答