javascript - 下载 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 执行的代码?
任何形式的帮助将非常感激
解决方案
您需要设置:responseType: 'blob'
。默认值为application/json
.
推荐阅读
- c++ - 有人可以告诉我这是如何在 main() 中实现的吗?(关于 void 指针的问题)
- azure - Service Fabric 单例服务在扩展时是否会停机?
- laravel - 我的 Laravel 路线不适用于 CentOS
- nlp - 使用经过训练的 K-Means 模型为未见数据预测正确的集群
- node.js - router.get 和 app.get 有什么区别?
- javascript - 如何使用 node.js 从 API 调用中打开数据并将数据写入文件
- mule - 在 Dataweave 2.0 中用空白替换 Null
- jquery - TS2702:“JQuery”仅指一种类型,但在此处用作命名空间
- c# - Azure Function App 无法加载 IOptionsFormatter
- android - 是否可以仅使用 cmake 构建本机 android 应用程序(ndk)?