Axios download file by the generated filename from the backend

Viewed 863

I am using Axios to send POST request to my backend.

The backend generate an Excel file with a name e.g. testing.xlsx.

What I am trying to do:

Doing this file using the same filename generated from the backend and I have tried Postman and everything works fine.

What I have tried:

axios.post(`${env.ENDPOINT}reports/sales/customers_statement`, {
    customers_id: form_data.customers_id,
    from_date: form_data.from_date,
    to_date: form_data.to_date,
  },{
    responseType: 'blob'
  }).then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data]));
    const link = document.createElement('a');
    const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`; // RENAME HERE
    link.href = url;
    link.setAttribute('download', file_name);
    document.body.appendChild(link);
    link.click();
    resolve(res.data);
  }).catch((e) => {
    reject(e);
  });

This works fine but it doesn't download the file by the filename generated from the server.

In other words I want to send request to my backend to download the file by the file name already generated from my backend like when I send request using Postman.

1 Answers

It is because you are setting the download attribute to file_name value which is different from the filename server returned

 const file_name = `${new Date().toISOString().slice(0,10)}.xlsx`; 

Try changing the above to this

const contentDisposition = data.headers['content-disposition'];
const filename = contentDisposition.match(/filename=(?<filename>[^,;]+);/)[0]; 
link.setAttribute('download', file_name);

In the backend

response.setHeader("Content-disposition", "attachment; filename="+ yourfilenamehere);
Related