本指南包含与管理共享云端硬盘相关的任务,例如创建 共享云端硬盘以及管理成员和权限。
如需详细了解共享云端硬盘的文件夹限制,请参阅文件夹 限制。
创建共享云端硬盘
如需创建共享云端硬盘,请使用 drives.create
方法。
Java
import com.google.api.client.googleapis.json.GoogleJsonResponseException; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.Drive; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.util.Arrays; import java.util.UUID; /* class to demonstrate use-case of Drive's create drive. */ public class CreateDrive { /** * Create a drive. * * @return Newly created drive id. * @throws IOException if service account credentials file not found. */ public static String createDrive() throws IOException { /*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/ GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( credentials); // Build a new authorized API client service. com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) .setApplicationName("Drive samples") .build(); Drive driveMetadata = new Drive(); driveMetadata.setName("Project Resources"); String requestId = UUID.randomUUID().toString(); try { Drive drive = service.drives().create(requestId, driveMetadata) .execute(); System.out.println("Drive ID: " + drive.getId()); return drive.getId(); } catch (GoogleJsonResponseException e) { // TODO(developer) - handle error appropriately System.err.println("Unable to create drive: " + e.getDetails()); throw e; } } }
Python
import uuid import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def create_drive(): """Create a drive. Returns: Id of the created drive Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() try: # create drive api client service = build("drive", "v3", credentials=creds) drive_metadata = {"name": "Project Resources"} request_id = str(uuid.uuid4()) # pylint: disable=maybe-no-member drive = ( service.drives() .create(body=drive_metadata, requestId=request_id, fields="id") .execute() ) print(f'Drive ID: {drive.get("id")}') except HttpError as error: print(f"An error occurred: {error}") drive = None return drive.get("id") if __name__ == "__main__": create_drive()
Node.js
/** * Create a drive. * */ async function createDrive() { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const uuid = require('uuid'); const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); const driveMetadata = { name: 'Project resources', }; const requestId = uuid.v4(); try { const Drive = await service.drives.create({ resource: driveMetadata, requestId: requestId, fields: 'id', }); console.log('Drive Id:', Drive.data.id); return Drive.data.id; } catch (err) { // TODO(developer) - Handle error throw err; } }
PHP
use Google\Client; use Google\Service\Drive; use Ramsey\Uuid\Uuid; function createDrive() { try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); $driveMetadata = new Drive\Drive(array( 'name' => 'Project Resources')); $requestId = Uuid::uuid4()->toString(); $drive = $driveService->drives->create($requestId, $driveMetadata, array( 'fields' => 'id')); printf("Drive ID: %s\n", $drive->id); return $drive->id; } catch(Exception $e) { echo "Error Message: ".$e; } }
.NET
using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Drive.v3.Data; using Google.Apis.Services; namespace DriveV3Snippets { // Class to demonstrate use of Drive's create drive. public class CreateDrive { /// <summary> /// Create a drive. /// </summary> /// <returns>newly created drive Id.</returns> public static string DriveCreateDrive() { try { /* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); var driveMetadata = new Drive() { Name = "Project Resources" }; var requestId = Guid.NewGuid().ToString(); var request = service.Drives.Create(driveMetadata, requestId); request.Fields = "id"; var drive = request.Execute(); Console.WriteLine("Drive ID: " + drive.Id); return drive.Id; } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found"); } else { throw; } } return null; } } }
对 drives.create
方法的调用包括
幂等性。
requestId
参数用于标识创建共享对象的逻辑尝试
。如果请求超时或返回不确定的后端错误,
可以重复相同的请求requestId
和请求正文必须
保持不变
如果该共享云端硬盘是根据之前的请求成功创建的,或是因为
则会返回正常响应。有时,例如在长时间
或者如果请求正文已更改,则可能导致 409
错误
返回,表示必须舍弃 requestId
。
添加或移除共享云端硬盘成员
通过以下方式添加或移除共享云端硬盘成员:
permissions
资源。
如要添加成员,请在共享云端硬盘中创建权限。权限 方法也可以对共享云端硬盘中的个别文件使用 或允许非成员协同处理 特定内容。
有关详情和示例代码,请参阅共享文件、文件夹和 驾车。
删除共享云端硬盘
使用 drives.delete
方法删除
共享云端硬盘。必须将共享云端硬盘中的所有内容移至回收站或删除
然后再删除共享云端硬盘。
为网域管理员管理共享云端硬盘
将 useDomainAdminAccess
参数与 drives
和 permissions
资源应用在一起,以跨
组织。
使用 useDomainAdminAccess=true
调用这些方法的用户必须拥有
Drive and Docs
管理员
权限。
管理员可以搜索
或更新共享云端硬盘的权限
其组织拥有的云端硬盘,无论管理员的成员资格如何
共享存储空间。
恢复没有组织者的共享云端硬盘
以下示例演示了如何使用这些资源恢复共享 没有组织者的云端硬盘。
Java
import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.drive.DriveScopes; import com.google.api.services.drive.model.Drive; import com.google.api.services.drive.model.DriveList; import com.google.api.services.drive.model.Permission; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* class to demonstrate use-case of Drive's shared drive without an organizer. */ public class RecoverDrive { /** * Find all shared drives without an organizer and add one. * * @param realUser User's email id. * @return All shared drives without an organizer. * @throws IOException if shared drive not found. */ public static List<Drive> recoverDrives(String realUser) throws IOException { /*Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application.*/ GoogleCredentials credentials = GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE)); HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter( credentials); // Build a new authorized API client service. com.google.api.services.drive.Drive service = new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(), GsonFactory.getDefaultInstance(), requestInitializer) .setApplicationName("Drive samples") .build(); List<Drive> drives = new ArrayList<Drive>(); // Find all shared drives without an organizer and add one. // Note: This example does not capture all cases. Shared drives // that have an empty group as the sole organizer, or an // organizer outside the organization are not captured. A // more exhaustive approach would evaluate each shared drive // and the associated permissions and groups to ensure an active // organizer is assigned. String pageToken = null; Permission newOrganizerPermission = new Permission() .setType("user") .setRole("organizer"); newOrganizerPermission.setEmailAddress(realUser); do { DriveList result = service.drives().list() .setQ("organizerCount = 0") .setFields("nextPageToken, drives(id, name)") .setUseDomainAdminAccess(true) .setPageToken(pageToken) .execute(); for (Drive drive : result.getDrives()) { System.out.printf("Found drive without organizer: %s (%s)\n", drive.getName(), drive.getId()); // Note: For improved efficiency, consider batching // permission insert requests Permission permissionResult = service.permissions() .create(drive.getId(), newOrganizerPermission) .setUseDomainAdminAccess(true) .setSupportsAllDrives(true) .setFields("id") .execute(); System.out.printf("Added organizer permission: %s\n", permissionResult.getId()); } drives.addAll(result.getDrives()); pageToken = result.getNextPageToken(); } while (pageToken != null); return drives; } }
Python
import google.auth from googleapiclient.discovery import build from googleapiclient.errors import HttpError def recover_drives(real_user): """Find all shared drives without an organizer and add one. Args: real_user:User ID for the new organizer. Returns: drives object Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for the application. """ creds, _ = google.auth.default() try: # create drive api client service = build("drive", "v3", credentials=creds) drives = [] # pylint: disable=maybe-no-member page_token = None new_organizer_permission = { "type": "user", "role": "organizer", "emailAddress": "user@example.com", } new_organizer_permission["emailAddress"] = real_user while True: response = ( service.drives() .list( q="organizerCount = 0", fields="nextPageToken, drives(id, name)", useDomainAdminAccess=True, pageToken=page_token, ) .execute() ) for drive in response.get("drives", []): print( "Found shared drive without organizer: " f"{drive.get('title')}, {drive.get('id')}" ) permission = ( service.permissions() .create( fileId=drive.get("id"), body=new_organizer_permission, useDomainAdminAccess=True, supportsAllDrives=True, fields="id", ) .execute() ) print(f'Added organizer permission: {permission.get("id")}') drives.extend(response.get("drives", [])) page_token = response.get("nextPageToken", None) if page_token is None: break except HttpError as error: print(f"An error occurred: {error}") return drives if __name__ == "__main__": recover_drives(real_user="gduser1@workspacesamples.dev")
Node.js
/** * Find all shared drives without an organizer and add one. * @param{string} userEmail user ID to assign ownership to * */ async function recoverDrives(userEmail) { // Get credentials and build service // TODO (developer) - Use appropriate auth mechanism for your app const {GoogleAuth} = require('google-auth-library'); const {google} = require('googleapis'); const auth = new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/drive', }); const service = google.drive({version: 'v3', auth}); const drives = []; const newOrganizerPermission = { type: 'user', role: 'organizer', emailAddress: userEmail, // Example: 'user@example.com' }; let pageToken = null; try { const res = await service.drives.list({ q: 'organizerCount = 0', fields: 'nextPageToken, drives(id, name)', useDomainAdminAccess: true, pageToken: pageToken, }); Array.prototype.push.apply(drives, res.data.items); for (const drive of res.data.drives) { console.log( 'Found shared drive without organizer:', drive.name, drive.id, ); await service.permissions.create({ resource: newOrganizerPermission, fileId: drive.id, useDomainAdminAccess: true, supportsAllDrives: true, fields: 'id', }); } pageToken = res.nextPageToken; } catch (err) { // TODO(developer) - Handle error throw err; } return drives; }
PHP
use Google\Client; use Google\Service\Drive; use Ramsey\Uuid\Uuid; function recoverDrives() { try { $client = new Client(); $client->useApplicationDefaultCredentials(); $client->addScope(Drive::DRIVE); $driveService = new Drive($client); $realUser = readline("Enter user email address: "); $drives = array(); // Find all shared drives without an organizer and add one. // Note: This example does not capture all cases. Shared drives // that have an empty group as the sole organizer, or an // organizer outside the organization are not captured. A // more exhaustive approach would evaluate each shared drive // and the associated permissions and groups to ensure an active // organizer is assigned. $pageToken = null; $newOrganizerPermission = new Drive\Permission(array( 'type' => 'user', 'role' => 'organizer', 'emailAddress' => 'user@example.com' )); $newOrganizerPermission['emailAddress'] = $realUser; do { $response = $driveService->drives->listDrives(array( 'q' => 'organizerCount = 0', 'fields' => 'nextPageToken, drives(id, name)', 'useDomainAdminAccess' => true, 'pageToken' => $pageToken )); foreach ($response->drives as $drive) { printf("Found shared drive without organizer: %s (%s)\n", $drive->name, $drive->id); $permission = $driveService->permissions->create($drive->id, $newOrganizerPermission, array( 'fields' => 'id', 'useDomainAdminAccess' => true, 'supportsAllDrives' => true )); printf("Added organizer permission: %s\n", $permission->id); } array_push($drives, $response->drives); $pageToken = $response->pageToken; } while ($pageToken != null); return $drives; } catch(Exception $e) { echo "Error Message: ".$e; } }
.NET
using Google.Apis.Auth.OAuth2; using Google.Apis.Drive.v3; using Google.Apis.Drive.v3.Data; using Google.Apis.Services; namespace DriveV3Snippets { // Class to demonstrate use-case of Drive's shared drive without an organizer. public class RecoverDrives { /// <summary> /// Find all shared drives without an organizer and add one. /// </summary> /// <param name="realUser">User ID for the new organizer.</param> /// <returns>all shared drives without an organizer.</returns> public static IList<Drive> DriveRecoverDrives(string realUser) { try { /* Load pre-authorized user credentials from the environment. TODO(developer) - See https://developers.google.com/identity for guides on implementing OAuth2 for your application. */ GoogleCredential credential = GoogleCredential.GetApplicationDefault() .CreateScoped(DriveService.Scope.Drive); // Create Drive API service. var service = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Drive API Snippets" }); var drives = new List<Drive>(); // Find all shared drives without an organizer and add one. // Note: This example does not capture all cases. Shared drives // that have an empty group as the sole organizer, or an // organizer outside the organization are not captured. A // more exhaustive approach would evaluate each shared drive // and the associated permissions and groups to ensure an active // organizer is assigned. string pageToken = null; var newOrganizerPermission = new Permission() { Type = "user", Role = "organizer", EmailAddress = realUser }; do { var request = service.Drives.List(); request.UseDomainAdminAccess = true; request.Q = "organizerCount = 0"; request.Fields = "nextPageToken, drives(id, name)"; request.PageToken = pageToken; var result = request.Execute(); foreach (var drive in result.Drives) { Console.WriteLine(("Found abandoned shared drive: {0} ({1})", drive.Name, drive.Id)); // Note: For improved efficiency, consider batching // permission insert requests var permissionRequest = service.Permissions.Create( newOrganizerPermission, drive.Id ); permissionRequest.UseDomainAdminAccess = true; permissionRequest.SupportsAllDrives = true; permissionRequest.Fields = "id"; var permissionResult = permissionRequest.Execute(); Console.WriteLine("Added organizer permission: {0}", permissionResult.Id); } pageToken = result.NextPageToken; } while (pageToken != null); return drives; } catch (Exception e) { // TODO(developer) - handle error appropriately if (e is AggregateException) { Console.WriteLine("Credential Not found"); } else { throw; } } return null; } } }
文件夹限制
共享云端硬盘文件夹的存储空间有一定的限制。有关信息,请参阅共享的 CANNOT TRANSLATE Google 云端硬盘。
内容上限
用户共享云端硬盘中每个文件夹的内容上限为 50 万项,包括 文件、文件夹和快捷方式。
达到上限后,共享云端硬盘将无法再接受内容。接收者 再次接收文件,用户必须从文件夹中永久删除内容。注意事项 回收站中的内容会计入上限,但会被永久删除 错误。有关详情,请参阅将文件移到回收站或删除 文件夹。
文件夹深度限制
共享云端硬盘中的文件夹包含的嵌套文件夹层级不能超过 100 层。 也就是说,子文件夹中存储的文件夹大小不能超过 共 99 层,此限制仅适用于子文件夹。
如果尝试添加超过 100 层的文件夹,
teamDriveHierarchyTooDeep
HTTP 状态代码响应。