使用Google App脚本在G Suite共享驱动器中创建Google Document快捷方式

时间:2020-10-05 13:00:34

标签: google-apps-script google-api shortcut

我可以使用“我的云端硬盘”中的快捷方式或“我的云端硬盘”中的文件夹轻松创建Google文档文件的快捷方式。这个问题和答案How to create a shortcut in Google Drive Apps Script instead of multiple parents

对此提供了极大帮助

但是,当我尝试对G Suite共享云端硬盘文件夹执行相同操作时,出现以下错误:

GoogleJsonResponseException:对drive.files.insert的API调用失败 出现错误:找不到文件:#FILE NUM

与“我的云端硬盘”一起使用,但不能与共享驱动器一起使用的代码是:

function createShortcut() {

  const targetId = "TARGET DOCUMENT ID"; 
  const shortcutName = "Test"; 
  const folderId = "TARGET FOLDER ID";
 
  const resource = {
    shortcutDetails: { targetId: targetId },
    title: shortcutName,
    mimeType:"application/vnd.google-apps.shortcut",
    supportsTeamDrives:true,
    parents: [{id: folderId}]
  };

  const shortcut = Drive.Files.insert(resource);
}

我已经查阅了文档https://developers.google.com/drive/api/v3/shortcuts,但没有运气。

1 个答案:

答案 0 :(得分:0)

问题

您将在文件资源中包含supportsTeamDrives参数。首先,不推荐使用此参数,如文档所示:现在您将使用supportsAllDrives。其次,请求主体(您称为resource的主体)和请求参数之间存在差异。

解决方案

如果您查看Drive.Files.insert()函数签名,您会发现有3个选项:

  • .insert(File resource);
  • .insert(File resource, Blob mediaData);
  • .insert(File resource, Blob mediaData, Object optionalArgs);

您使用的是第一个,因此不允许指定任何请求参数。因此,您应该使用第三个。

在您的情况下,如何使用它:

// Since you are not creating nor uploading any file you shall leave the Blob mediatada parameter as null
 const resource = {
    shortcutDetails: { targetId: targetId },
    title: shortcutName,
    mimeType:"application/vnd.google-apps.shortcut",
    parents: [{id: folderId}]
  };
  
  const options = { supportsAllDrives: true };

  const shortcut = Drive.Files.insert(resource, null, options);

参考

Files v2 insert