将文件上传到 Google Team Drive

Upload file to Google Team Drive

我已经在互联网上搜索了几个小时,试图找出上传将包含在团队云端硬盘中的文件所必需的内容。

我已经阅读了大部分文档,我发现的唯一有趣的部分/提到的团队驱动器在这里,但不幸的是没有细节:
https://developers.google.com/drive/v3/web/manage-uploads
https://developers.google.com/drive/v3/web/manage-teamdrives
https://developers.google.com/drive/v3/web/about-files

我正在使用 .Net gapi nuget 包 (v3)。创建如下服务:

string[] scopes = new string[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
var secrets = new ClientSecrets
{
    ClientId = "...",
    ClientSecret = "...",
};
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, Environment.UserName, CancellationToken.None).Result;
var service = new DriveService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "...",
});

我有我要定位的TeamDrive的Id,我可以通过下面的代码成功检索TeamDrive,但是这里没有有趣的上传方法:

var teamDrive = service.Teamdrives.Get(driveFolderId).Execute();

我目前一直在尝试使用正常的 CreateMediaUpload 方式创建文件。

File body = new File();
body.Name = name;
body.MimeType = "application/octet-stream";
FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, "text/plain");
request.Upload();

File 上有一些有趣的属性,即 ParentsTeamDriveId。将 TeamDriveId 设置为 Team Drive Id 时,该文件最终位于我个人驱动器的根目录中。将父级设置为 Team Drive Id 时,我似乎无法在任何地方找到该文件。

没有抛出任何错误,request.Upload() 的结果每次都指示 Success/Complete(即使文件没有显示)。我还应该在哪里寻找设置父团队的动力? FileDriveServiceTeamDrive 上没有其他有趣的属性,所以我很迷茫。

除了将父级设置为团队驱动器 ID 外,您还必须在请求中将 SupportsTeamDrives 属性 设置为 true。

代码将类似于以下内容(我已经注意到重要的几行):

File body = new File();
body.Name = name;
body.MimeType = "application/octet-stream";
body.Parents = new List<string> { driveFolderId }; // <--------

FilesResource.CreateMediaUpload request = service.Files.Create(body, stream, "application/octet-stream");
request.SupportsTeamDrives = true;                 // <--------
request.Upload();

这里的关键是团队驱动器权限方案与个人驱动器权限方案完全不同,因此您需要明确选择加入以证明您了解差异。

额外的信息,如果您想列出或搜索团队驱动器中的文件,您还必须在请求中指定 IncludeTeamDriveItemsCorpora(除了 SupportsTeamDrives).

搜索结果可能如下所示

var existingSearch = service.Files.List();
existingSearch.Fields = "nextPageToken, files(id, name)";
existingSearch.Q = $"'{driveFolderId}' in parents and name = '{name}'";
if (isFolderTeamDrive)
{
    existingSearch.SupportsTeamDrives = true;
    existingSearch.Corpora = "teamDrive";
    existingSearch.IncludeTeamDriveItems = true;
    existingSearch.TeamDriveId = driveFolderId;
}

var existingResponse = existingSearch.Execute();