Home > OS >  Download XLSX via Axios from Express.js server does not work
Download XLSX via Axios from Express.js server does not work

Time:03-27

Server:

return res.download(filepath);

Client:

function provideDownload(filename, data) {
  const linkElement = document.createElement('a');
  linkElement.setAttribute('href', data);
  linkElement.setAttribute('download', filename);
  document.body.appendChild(linkElement);
  linkElement.click();
  linkElement.remove();
}

function provideBlobDownload(filename, data) {
  provideDownload(
    filename,
    window.URL.createObjectURL(new Blob([data]))
  );
}

axios.post('/export', {
  entity, fileformat, locale: props.locale,
}).then((res) => {
  provideBlobDownload(filename, res.data);
});

Problem:

Can't open downloaded xlsx file. Message: File might be corrupted.

API response in browser console looks like:

UEsDBAoAAAAAAPC1eVTWknwRWgEAAFoBAAARAAAAZG9jU....

I have already read through related posts including this one How to save .xlsx data to file as a blob but I couldn't solve it.

I'd like to solve it without using an additional package like exceljs

CodePudding user response:

try adding responseType:'blob' to request config option:

axios.post('/export', {
    entity,
    fileformat,
    locale: props.locale
}, {
    responseType: 'blob'
})
.then((res) => {
    provideBlobDownload(filename, res.data);
});
  • Related