warCommander
warCommander

Reputation: 449

how to download an excel file in react from NodeJS

I have a nodeJs server and react app. and in my NodeJs I am returning an excel file and I was able to download it in postman when clicking send and download. But in react the file is download but give error when openning that it is corrupt

Here is my implementation in ReactJS (Thats making the issue)

export const exportUsersToExcel = async (token) => {
      try {
        axios
          .get(
            `${process.env.REACT_APP_SERVER}/api/dashboard/users/excel`,
            {
              headers: { "auth-token": token },
            },
            { responseType: "blob" }
          )
          .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement("a");
            link.href = url;
            link.setAttribute("download", "Users.xlsx");
            document.body.appendChild(link);
            link.click();
          });
      } catch (error) {
        console.log("Error Exporting Users");
        return error;
      }
    };

and I am sending the file in NodeJS like this

    res.set({
      "Content-disposition": `attachment; filename=Users.xlsx`,
      "Content-Type":
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });

    return workbook.xlsx.write(res).then(() => {
      res.status(200).end();
    });

Upvotes: 3

Views: 6220

Answers (1)

Roger Inacio
Roger Inacio

Reputation: 83

I had a similar problem, and I solved it with the following (React) code:

Axios

export const getFile = async () => {
  return await api.get<any>(`${PATH_API}`, {
    responseType: 'arraybuffer',
    headers: {'Content-Type': 'blob'},
  });
};

Function in .tsx file

const downloadFile = async () => {
    const resp = await getFile();

    const link = document.createElement('a');
    const fileName = 'file.extension';
    link.setAttribute('download', fileName);
    link.href = URL.createObjectURL(new Blob([resp.data]));
    document.body.appendChild(link);
    link.click();
    link.remove();
  };

Render function

<a onClick={() => downloadExceptionFile()} href="#" download>
download
</a>

The ploblem with this is that URL.createObjectURL() is deprecated. I don't know how to resolve this at this point.

Upvotes: 6

Related Questions