【问题标题】:Download Excel works in Postman but doesn't in Javascript下载 Excel 在 Postman 中有效,但在 Javascript 中无效
【发布时间】:2021-05-19 08:37:08
【问题描述】:

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

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

这似乎是二进制的。在 Postman 中,我可以设置令牌并单击 Save and download 按钮,一切正常。现在,这是我在 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 执行的代码?

任何形式的帮助都将不胜感激

【问题讨论】:

  • 尝试设置responseType: 'stream'responseType: 'blob'。默认为application/json
  • 非常感谢! responseType: 'blob' 成功了!如果您想回答被选为已接受的回答并关闭此问题!
  • 很高兴听到。好的

标签: javascript axios postman


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2020-04-28
    • 2020-04-06
    • 2019-11-28
    • 2020-10-15
    • 2017-05-03
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多