【问题标题】:How to download document from google drive in React js?如何在 React js 中从谷歌驱动器下载文件?
【发布时间】:2023-01-11 18:33:06
【问题描述】:

我在一个教育技术平台上工作。在这种情况下,学生可以从前端查看和下载他/她的大厅门票。大厅门票存储在谷歌驱动器中。并且 URL 存储在数据库中。我们得到 URL,我们在前端显示预览文件,简单。但是你能帮我下载功能吗?

显示大厅门票的对话组件

<DialogAtom
        isOpen={openHallTicket}
        maxWidth="lg"
        customClass={classes.imageModal}
        closeOnBlur={() => setopenHallTicket(false)}
        content={(
          <DialogContent
            p={0}
          >
            <Grid container className={classes.imageSec}>
              <Grid item xs={12} className={classes.rightIcons} display="flex" alignItems="center" justifyContent="flex-end">
                <ThemeProvider theme={toolTipTheme}>
                  <Tooltip title={t('PRINT')}>
                    <IconButton onClick={handlePrintHallTicket}>
                      <PrintIcon />
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={t('DOWNLOAD')}>
                    <IconButton className={classes.downloadIcon} onClick={(e) => download()}>
                      {/* <a
                        href={HallTicketImage}
                        download
                      > */}
                        <FileDownloadOutlinedIcon />
                      {/* </a> */}
                    </IconButton>
                  </Tooltip>
                  <Tooltip title={t('CLOSE')}>
                    <IconButton
                      className={classes.emailIcon}
                      onClick={() => setopenHallTicket(false)}
                    >
                      <CloseIcon />
                    </IconButton>
                  </Tooltip>
                </ThemeProvider>
              </Grid>
              {/* <iframe src="https://drive.google.com/file/d/<uniqueId>/preview" width="640" height="480" allow="autoplay"></iframe> */}
              <CardMedia
                ref={componentRefHallTicket}
                component="iframe"
                sx={{height : '50rem'}}
                // className={classes.profileImg}
                // component="img"
                // image={HallTicketImage}
                // image={() => {<iframe src='https://drive.google.com/file/d/<uniqueId>/view'/>}}
                // image={<iframe src="https://drive.google.com/file/d/<uniqueId>/preview" width="640" height="480" allow="autoplay"></iframe>}
                image='https://drive.google.com/file/d/<uniqueId>/preview'
                // image='https://drive.google.com/file/d/<uniqueId>/view'
                alt="certificate"
              />
            </Grid>
          </DialogContent>

这会产生这样的东西

下载这个 -->

  const download = (e) => {
    fetch('https://drive.google.com/u/1/uc?id=<uniqueId>&export=download', {
      method: 'POST',
      headers: {
        authorization: <uniqueAuth>
      },
    })
      .then((response) => {
        response.arrayBuffer().then((buffer) => {
          const url = window.URL.createObjectURL(new Blob([buffer]));
          const link = document.createElement('FileDownloadOutlinedIcon');
          link.href = url;
          link.setAttribute('download', 'image.png'); // or any other extension
          document.body.appendChild(link);
          link.click();
        });
      });
  };
  // const downloadFile = () => {
  //   fetch("https://drive.google.com/file/d/<uniqueId>/preview")
  //     .then((response) => response.blob())
  //     .then((blob) => {
  //       const link = document.createElement('a');
  //       link.href = URL.createObjectURL(blob);
  //       link.download = resourceName;
  //       link.click();
  //     });
  // };

这是下载按钮

请帮我

【问题讨论】:

  • 文件的 mimeType 是什么?
  • mimeType 是 pdf
  • 谢谢你的回复。根据您的回复,我提出了一个修改后的脚本作为答案。请证实。如果那没有用,我深表歉意。

标签: reactjs google-cloud-platform google-drive-api


【解决方案1】:

mimeType is pdf,我了解到您要下载的文件的mimeType 是application/pdf

修改点:

  • 在这种情况下,使用 GET 方法。
  • 来自mimeType is pdf,当您的访问令牌是下载文件的有效令牌时,使用https://www.googleapis.com/drive/v3/files/###fileId###?alt=media 的端点如何?
  • 在这种情况下,image.png 可能是 ###.pdf

当这些点反映在您的脚本中时,如何进行以下修改?

修改脚本:

从:

fetch('https://drive.google.com/u/1/uc?id=<uniqueId>&export=download', {
  method: 'POST',
  headers: {
    authorization: <uniqueAuth>
  },
})
  .then((response) => {
    response.arrayBuffer().then((buffer) => {
      const url = window.URL.createObjectURL(new Blob([buffer]));
      const link = document.createElement('FileDownloadOutlinedIcon');
      link.href = url;
      link.setAttribute('download', 'image.png'); // or any other extension
      document.body.appendChild(link);
      link.click();
    });
  });

到:

请设置您的文件 ID 和访问令牌。

fetch('https://www.googleapis.com/drive/v3/files/###fileId###?alt=media', {headers: { authorization: "Bearer ###yourAccessToken###" }})
  .then((response) => {
    response.arrayBuffer().then((buffer) => {
      const url = window.URL.createObjectURL(new Blob([buffer]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', 'sample.pdf'); // or any other extension
      document.body.appendChild(link);
      link.click();
    });
  });

笔记:

  • 在此修改中,您的访问令牌&lt;uniqueAuth&gt; 是下载文件的有效令牌。请注意这一点。

参考:

【讨论】:

  • 显示 CORS 错误
【解决方案2】:

这是工作

onClick={(e) => {window.open("https://drive.google.com/u/1/uc?id=<fileId>&export=download", "_blank");}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2021-04-05
    • 2018-07-21
    • 1970-01-01
    • 2018-01-12
    相关资源
    最近更新 更多