I am working with React Js and Axios to make requests to an API. I am trying to download files via API with ReactJs, but when they download and try to open, I get an error message: 'the file is damaged or damaged'.
The files are obtained through a GET request and can be of type pdf, xlxs, docx and others), and the mime is obtained through props that comes from a parent component
This is my code (a part of my component)
fetchFile(){
axios
.get(`/someurl/thefiles/${this.props.file.id}`, { headers })
.then(response => {
let url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download",
`${this.props.file.name}.${this.props.file.mime}`);
document.body.appendChild(link);
link.click();
});
}
render(){
return(
<button onClick={this.fetchFile}> Download file </button>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
The mime and filename come from a parent component.
The problem I have is that I download a file, xlsx for example, and when I open it I get an error box with the message 'The file is damaged', if I download a pdf file, it downloads without problem and when I open the pdf is completely blank: the same number of sheets as the original but all white.
I am trying from chrome, firefox and brave and the error is the same