In my react app, I have a component which has a file download button for download a file coming from the Back end. I'm using AXIOS
for the AJAX
call. The problem is, after downloading the file, it is corrupted. I'm downloading png
files and pdf
files. When I open the downloaded image, it says it's corrupted and downloaded pdf
shows white background only. How can I download a file correctly?
** Component:**
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 file:
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"
}
});