在我的 React 应用程序中,我有一个组件,它有一个文件下载按钮,用于下载来自后端的文件。我正在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"
}
});