首页 > 解决方案 > 下载 Excel 在 Postman 中有效,但在 Javascript 中无效

问题描述

我正在尝试通过 AJAX(使用 Axios)下载 Excel 文件。我这样做是因为我需要发送一个 JWT 令牌来访问它。

现在,我收到了一个文件响应,内容如下:

收到的数据

这似乎是二进制的。在 Postman 中,我可以设置令牌并单击保存和下载按钮,一切正常。现在,这是我在 JS 中的代码:

requestWithFullResponse({
  url: url,
  method: 'GET',
}, this.props.token, false).then((response) => {
  const responseData = response.data

  // I've tried with different types and nothing works
  // var blob = new Blob([responseData], { type: `${response.headers['content-type']};charset=utf-8` });
  // var blob = new Blob([responseData], { type: 'application/octet-stream;charset=utf-8' });
  var blob = new Blob([responseData], { type: 'application/octet-stream' });

  saveAs(blob, filename, true)
}).catch((error) => { console.log('Error downloading file -> ', error); });

该代码下载文件,但是当我打开它时,Libre Office 说文件已损坏。我错过了什么?有没有办法在下载文件时查看 Postman 执行的代码?

任何形式的帮助将非常感激

标签: javascriptaxiospostman

解决方案


您需要设置:responseType: 'blob'。默认值为application/json.


推荐阅读