How to download exported excel from laravel using axios? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to download exported excel from laravel using axios? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have my code below from Backend that is working fine when I test it using Laravel’s blade. But I can’t do the same in using Axios in my React frontend (see frontend code below).

return (new NewsExport())->download($filename);

I somehow found some solutions from another site: they change the backend code, they use the Storage method to return a link instead of a file. But I don’t want to use Storage, I want to prevent overstoring files (in case of a user in the frontend rapidly clicks the download button).

My question how can we download the returned file from the backend in the frontend Axios?


My frontend codes (the codes below successfully download an excel file, but the file is corrupted I think because I can’t open it when I test it using Microsoft Excel)

let response = await newsApi.exportNewsList(payload).then(response => {
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'exc.xlsx'); //or any other extension
    document.body.appendChild(link);
    link.click();
});

Here is the response.data when I log: screenshot

Answer

I think you forgot to specify your responseType as blob in your api options.

const options = {
    method: 'POST',
    responseType: 'blob', <=== you need this one
    data: formData,
    url: '/yourApi',
};

return API.request(options);
We are here to answer your question about How to download exported excel from laravel using axios? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji