首页 > 解决方案 > 如何将(PDF,二进制)文件从 GAS Web 服务到浏览器?

问题描述

我的 Google 应用程序脚本创建 PDF 文件。我想让用户下载它。我想让每个人都更容易,所以我认为 Web 应用程序将是一个不错的选择。所以我开始用谷歌搜索解决方案,但我找不到任何有用的东西。

理想情况下,我希望网络用户输入触发 PDF 文件创建的代码(该部分已准备好 - PDF 位于 Google Drive 中),然后通过网络浏览器将文件下载到最终用户计算机。

这可以通过在 Google 应用程序脚本中创建的网络实现吗?

从这个答案中我发现我正在寻找的东西是不可能的https://stackoverflow.com/a/36701196/250422

我找到的最接近的解决方案是google-web-app-script-to-auto-download-from-google-drive

标签: google-apps-script

解决方案


我相信你的目标如下。

  • 您想让用户使用用户的浏览器下载 PDF 文件。
  • 您想使用由 Google Apps 脚本创建的 Web 应用程序来实现此目的。

在这种情况下,下面的示例脚本怎么样?在此示例脚本中,PDF 文件被转换为数据 URL,并让用户使用浏览器下载为 PDF 文件。

示例脚本:

Google Apps 脚本方面:Code.gs

请将以下脚本复制并粘贴到脚本编辑器中Code.gs。并且,请设置 PDF 文件的文件 ID。并且,请部署 Web Apps

function doGet() {
  return HtmlService.createHtmlOutputFromFile("index");
}

function createDataUrl() {
  const fileId = "###"; // Please set the file ID of the PDF file you want to make user download.
  const file = DriveApp.getFileById(fileId);
  return {
    data: `data:${file.getMimeType()};base64,${Utilities.base64Encode(file.getBlob().getBytes())}`,
    filename: file.getName(),
  };
}

HTML&Javascript 方面:index.html

请将以下脚本复制并粘贴到脚本编辑器中index.html

<input type="button" value="download" onclick="download()" />
<script>
  function download() {
    google.script.run
      .withSuccessHandler(({ data, filename }) => {
        if (data && filename) {
          const a = document.createElement("a");
          document.body.appendChild(a);
          a.download = filename;
          a.href = data;
          a.click();
        }
      })
      .createDataUrl();
  }
</script>
  • 在这种情况下,当您使用浏览器访问已部署的 Web 应用程序并单击“下载”按钮时,PDF 文件将下载到您的本地 PC。

笔记:

参考:


推荐阅读