【发布时间】: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