代码之家  ›  专栏  ›  技术社区  ›  Michael

文件夹getParents无法在Google脚本中获取团队驱动器名称

  •  2
  • Michael  · 技术社区  · 6 年前

    我正在尝试使用脚本在团队驱动中构建文档的完整路径。代码如下所示:

    var path = [ ]
    var folder = id.getParents()
    while (folder && folder.hasNext()) {
      var f = folder.next()
      path.unshift(f.getName())
      folder = f.getParents()
    }
    

    此脚本绑定到文档以进行测试。

    但当我找到根时,它不是返回团队驱动力的实际名称,如“会计”或“营销”,而是返回“团队驱动力”。我需要知道 名称 为什么我没有得到这个信息?如果我在绑定到驱动器中文档的脚本中运行它,它会在根目录中显示“我的驱动器”——这至少有意义,因为这是我在浏览器中看到的实际名称。在团队驱动中,根实际上是“团队驱动”,而不是“团队驱动”。

    1 回复  |  直到 6 年前
        1
  •  5
  •   tehhowch    6 年前

    由于Team Drive的实现方式不同于“常规”Google Drive文件夹 DriveApp 不能保证在处理这些问题的所有操作中都能正常工作。有可能在某个时候 DriveApp 将进行更新,以完全支持团队驱动,但谷歌仍有许多明智的事情要做;)

    相反,请使用“高级服务” Drive ,这是一个客户端应用程序,它实现了驱动器REST API的版本2,并允许正确处理团队驱动器信息。作为“高级服务”,您 必须 enable this service 在你可以使用它之前。

    要仅使用高级服务构建团队驱动项目的完整路径,请执行以下操作:

    function getTeamDrivePath(fileId) {
      // Declare we know how to handle Team Drive items, and that they be included in responses.
      var params = {
        supportsTeamDrives: true,
        includeTeamDriveItems: true
      };
      // Return only the fields we want, instead of the whole `File` resource.
      params.fields = "id,title,parents/id"
    
      // In a Team Drive, a file can have only one parent folder (e.g. "normal" filesystems).
      // (parent.isRoot is never true for Team Drive folders so it is not used.)
      var path = [], file;
      do {
        file = Drive.Files.get(fileId, params);
        path.unshift(file.title);
        fileId = file.parents.length ? file.parents[0].id : null;
      } while (fileId);
    
      // Since we also added the file, the last element of the path array is the filename.
      path.pop();
    
      // A Team Drive is subject to different permissions than files, and thus its name must be 
      // obtained via the Team Drives resource. Since `file` points to the Team Drive, use it:
      // Requesting incorrect fields will result in an API error, so request the proper ones:
      params.fields = "name"
      var td = Drive.Teamdrives.get(file.id, params);
      path[0] = td.name;
      return path;
    }
    

    有关团队驱动器及其相关处理的更多信息,请参阅驱动器REST API参考。我链接了v2版本,因为它们是通过应用程序脚本的“高级服务”提供的,但v3版本应该用于使用客户端库的第三方应用程序。

    重要资源:

    推荐文章