Google Drive API 发布文档并获取发布链接

blu*_*yke 5 javascript node.js web google-drive-api

如果我在 Google 云端硬盘中创建文档并输入一些文本,我稍后可以转到 file => Publish to the Web 并获取指向google 文档的公共网页样式的链接以及嵌入链接。

这就是手动完成的方式。如何使用Goolgle Drive API通过Node.JS 服务器脚本(例如,使用服务帐户)自动执行此操作?我在他们的文档中找不到有关此特定事物的任何信息,这可能吗?我需要制作一个谷歌脚本吗?这可能吗?

Tan*_*ike 5

  • 您想要使用 googleapis 和 Node.js 将 Google 文档发布到网络。
  • 您想要检索已发布的 URL。
  • 您希望使用服务帐户来实现此目的。
  • 您已经拥有服务帐户并能够使用 Drive API。

从你的问题和回复评论中,我可以这样理解。如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

用法:

为了使用以下示例脚本,请执行以下流程。

  1. 准备一份 Google 文档。
    • 在这种情况下,作为测试用例,请在您的 Google 云端硬盘中创建新的 Google 文档。
  2. 使用服务帐户的电子邮件作为作者共享创建的 Google 文档。
  3. 检索 Google 文档的文件 ID。
  4. 将变量设置为以下示例脚本。
  5. 运行脚本。
    • 在这种情况下,使用Drive API的“修订:更新”。

这样,Google 文档就发布到了网络上,您可以在控制台看到发布的 URL。

示例脚本:

const { google } = require("googleapis");

// Please set the email and private key of service account.
const auth = new google.auth.JWT(
  "### email of service account ###",
  null,
  "### private key of service account ###" ,
  ["https://www.googleapis.com/auth/drive"]
);
const fileId = "###"; // Please set the file ID.

const drive = google.drive({ version: "v3", auth });
const body = {
  resource: {
    published: true,
    publishedOutsideDomain: true,
    publishAuto: true
  },
  fileId: fileId,
  revisionId: 1
};
drive.revisions.update(body, err => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(`https://docs.google.com/document/d/${fileId}/pub`);
});
Run Code Online (Sandbox Code Playgroud)
  • 请设置私钥,如"-----BEGIN PRIVATE KEY-----\n###\n-----END PRIVATE KEY-----\n"

笔记:

  • 发布的网址是https://docs.google.com/document/d/${fileId}/pub。在这种情况下,使用文件 ID。因为不幸的是,现阶段https://docs.google.com/document/d/e/2PACX-###/pubhtmlGoogle API无法检索到类似的URL。

参考: