javascript - 如何通过 React 中的 API 下载文件?
问题描述
在我的反应应用程序中,我有一个组件,它有一个文件下载按钮,用于下载来自后端的文件。我正在AXIOS
用于AJAX
通话。问题是,下载文件后,它已损坏。我正在下载png
文件和pdf
文件。当我打开下载的图像时,它说它已损坏并且下载pdf
仅显示白色背景。如何正确下载文件?
** 零件:**
import API from "../../api/api";
class DocumentsTable extends React.Component {
constructor(props) {
super(props);
this.state = {
fileId: 4
};
this.downloadMapById = this.downloadMapById.bind(this);
}
downloadMapById() {
const type = 1;
const file_id = this.state.fileId;
const FileDownload = require("js-file-download");
API.post("project/files/download", { file_id, type })
.then(({ data }) => {
FileDownload(data, "myImage.png");
console.log("success!", data);
})
.catch(err => {
console.log("AXIOS ERROR: ", err);
});
}
render() {
return <button onClick={() => this.downloadMapById}>Download</button>;
}
}
API文件:
import axios from "axios";
const token = localStorage.getItem("token");
export default axios.create({
baseURL: `${process.env.REACT_APP_BACKEND_BASE_URL}/api/v1/`,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
Accept: "application/json"
}
});
解决方案
由于我无法添加评论,因此发布为答案。我已经尝试过同样的事情,并在此链接中发布了同样的问题。
对于post方法,我通过fetch获得成功,如下所示。
fetch("url",
{
method: "POST",
headers: { "Content-Type": "application/json",'Authorization': 'Bearer ' + window.localStorage["Access_Token"]},
body:data
}).then(response => response.blob()).then(response => ...*your code for download*... )
您收到损坏的文件,因为您没有收到blob或arraybuffer的内容。
推荐阅读
- r - 比较三个分类列并用 0,1 或 2 表示结果
- r - 在函数 (R) 中将列内容设置为变量
- amazon-web-services - AWS Fargate 无法通过负载均衡器/公共 IP 访问 dockerized spring boot 应用程序
- php - 由于保护功能,调用方法尝试不起作用
- javascript - 如何在 .js 文件中使用 .ts 文件中的变量
- arrays - 尝试在 Flutter Streambuilder 中构建一个喜欢/不喜欢按钮 - 不工作
- nginx - 在 Synology nginx 反向代理后面不允许 Zammad 社区零星错误 405
- c# - CS0120 非静态字段需要对象引用
- javascript - 在特定时间后重定向到另一个页面并显示倒计时
- python - 通过查询内联替换 AST 节点