1

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:

Body of the response

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?

avocadoLambda
  • 1,332
  • 7
  • 16
  • 33
  • It sounds like you might be overcomplicating things. Please look [here](https://stackoverflow.com/a/56220866/421195), [here](https://stackoverflow.com/a/67465924/421195), or [here](https://stackoverflow.com/a/46331201/421195) – paulsm4 Aug 18 '21 at 21:31
  • 1
    Omg, the 3th answer was THE one! I had to put the attribute `responseType: 'arraybuffer'` in my Axios request. Thank you VERY MUCH, sir – João Bonsegno Aug 18 '21 at 22:10
  • My pleasure - glad I could help :) – paulsm4 Aug 18 '21 at 23:15

0 Answers0