There's a possible duplicate here, but I couldn't find my answer to any other question
I'm trying to download a file that comes from my API. My API endpoint returns me a content-type application/vnd.ms-excel
and the structure of my file in the body of the response. The file comes like this:
When I try it on Postman and click in the option Save Response
and then Save to a file
, everything works perfectly.
But when I try it on my React App, the file comes with those strange characters from the body of the response, instead of saving it as Postman does. I've tried a lot of different ways to save it, but it still doesn't work. Those are 3 ways I already tried to trigger the file download:
try {
const response = await api.get(`/portfolio/files?portfolio_id=${wallet.id}&portfolio_filename=${file.name}`, {
headers: {
'x-access-token': localStorage.getItem('token')
}
});
// 1st way
const blob = new Blob([response.data], { type: response.headers['content-type'] });
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = file.name.split['.'];
link.click();
// 2nd way
const url = window.URL.createObjectURL(new Blob([response.data], { type: response.headers['content-type'] }));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', file.name);
document.body.appendChild(link);
link.click();
// 3rd way
const blob = new Blob([response.data], { type: "octet/stream" });
fileSaver.saveAs(blob, file.name);
} catch(err) {
console.error(err);
}
// 3rd way
const blob = new Blob([response.data], { type: "octet/stream" });
fileSaver.saveAs(blob, file.name);
} catch(err) {
console.error(err);
}
I'm using a Blob to create a URL to my file, setting its content as the body of the response and its type as the content-type (which is application/vnd.ms-excel
, like I said before).
All those three ways always write those exact same symbols into the file, instead of downloading it normally, as Postman does.
Does anyone know what am I missing here?