简体   繁体   中英

xlsx file corrupted while downloading with the file-saver npm package

I am having a problem in downloading a xlsx file. My excel file is generated with js-xlsx . I have to add some authorization headers to verify the incoming requests on the server. For this reason, I can not just simply open the link in a new window from my client-side. For testing purpose, I try to download the file by directly hitting the browser link of my API endpoint (of course by removing the authorization middleware temporarily). The browser downloads the file without any problem or corruption. Unfortunately, this is not the case with the client-side download functionality while using filesaver.js through axios get request.

My snippet from the backend code where I am sending the response is:

 //..... Some code for writing the workBook

 const workBookOutput = xlsx.write(workBook, {
      bookType: 'xlsx',
      type: 'buffer'
    });
 const xlsxFileBuffer = Buffer.from(workBookOutput);

 // res is express HTTP response object
 res.set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
 res.set('Content-Disposition', 'attachment; filename=excel-export.xlsx');

 res.status(200).send(xlsxFileBuffer);

The part of my client-side code is:

const headers = {
 'Content-Type': 'application/json',
  Accept: 'application/json'
};

// here I add some real jwt token in my code, not the dummy that I have below
headers.authorization = `bearer asklndashduwkhd2oo832uejh32oihjdoasincas`;

const options = {
         'get',
          'https://myURLToAPi/api',
          headers,
          responseType: 'arraybuffer'
        }
const response = await axios(options);

//fileSaver is required above in file 

fileSaver.saveAs(
  new Blob([response.data], {
    type:
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  }),
  'excel.xlsx'
);

I still only get the corrupted file. I have tried multiple options on server and client-side both, nevertheless, the downloaded file always comes as corrupted. I have tried not making another Buffer.from after getting my workbookOutput still nothing has changed. Can someone help me in this regard? Am I missing something?

This is the picture of what I get for corrupt download if I try to open it.

在此处输入图片说明

I had a similar issue - I was generating Excel in Django, getting bytes then querying it using Axios. The Excel produced with FileSaver was corrupted, and, just like @Seeker mentioned, it was twice the size.

However I could get a normal file when testing in Postman. What solved my problem was setting

responseType: 'blob'

in axios options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM