【问题标题】:how to download an excel file in react from NodeJS如何从NodeJS下载一个excel文件以做出反应
【发布时间】:2022-01-26 06:22:47
【问题描述】:

我有一个 nodeJs 服务器和 react 应用程序。在我的NodeJs中,我返回了一个excel文件,单击发送和下载时,我可以在邮递员中下载它。但是在反应文件是下载但打开时出错,它已损坏

这是我在 ReactJS 中的实现(这就是问题所在)

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;
      }
    };

我正在像这样在 NodeJS 中发送文件

    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();
    });

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    我遇到了类似的问题,我用以下 (React) 代码解决了它:

    Axios

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

    .tsx 文件中的函数

    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();
      };
    

    渲染函数

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

    问题在于 URL.createObjectURL() 已被弃用。我现在不知道如何解决这个问题。

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 2019-09-01
      • 2019-03-10
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      相关资源
      最近更新 更多