0

I have an api response which return a xlsx file as response.

the api is triggered on button click and I need to download it as on response.

every api call is gone through a service which handles appends token to the url for authentication purposes.which basically means that I cannot use methods like this the one mentioned here. the response I am getting is like this ( response when debugged ). I have tried

a.href = window.URL.createObjectURL(response)

and

a.href = window.URL.createObjectURL(new blob([response]))

and tried downloading but but spreadsheet is corrupted ( I know the file is fine sice swagger returns the file properly).

how do I get this file as that of in swagger like this so that i can download in a.click().

this is my api from dot net

thank you in advance.

  • Have you tried something like this? ```const myLink = document.createElement('a'); myLink.href = window.URL.createObjectURL(blobFile); myLink.download = fileName; myLink.click();``` – Klian Mar 31 '23 at 18:07
  • @Klian response is not a blob file I think. That is another issue I am facing as well. not sure about the file type I am getting. when debugged it looks like https://i.stack.imgur.com/JgZ9e.png – Nabeel Mhd Mar 31 '23 at 18:15

1 Answers1

0

You can try using the FileSaver.js library to download the file.
Here is the sample code:

import FileSaver from 'file-saver';

// Call your API to get the response
axios.get('/PrintWorkSheet', { responseType: 'arraybuffer' }).then((response) => 
    {
        //Create a Blob object from the response data
        const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // Use FileSaver.js to save the Blob as a file
        FileSaver.saveAs(blob, 'WorkSheet.xlsx');
    })
    .catch((error) => {
        console.log(error);
    });
Xiaotian Yang
  • 499
  • 1
  • 2
  • 7