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"
}
});
In this article, I will use a demo Web API application in ASP.NET Core to show you how to transmit files through an API endpoint. In the final HTML page, end users can left-click a hyperlink to download the file or right-click the link to choose “ Save Link As ” in the context menu and save the file.
Download Text file You can enter the required text in the input field and download it as a text file by clicking the download button. A new Blob Object of the MIME type will be created and attaches it to the href of a temporary anchor element and will be triggered programmatically.
To download a file with React. js, we can add the download attribute to an anchor element. We just add the download prop to do the download. If we don't want to use an anchor element, we can also use the file-saver package to download our file.
As I am not able to add comments so posting as answer. I have tried the same thing and posted the question for same in this link.
For post method i get the success with fetch as below.
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*... )
You are getting corrupted file because you are not receiving content as blob or arraybuffer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With