如何使用Google API在Team Drive中创建文件夹?

时间:2017-07-26 13:00:22

标签: php google-api google-drive-api google-api-php-client

我很难使用Google API PHP客户端库在Team Drive中创建文件夹。

我正在使用服务帐户并模仿作为Team Drive成员的用户(我自己)并可以列出驱动器的内容。但是,当我创建一个文件夹时,它总是在“我的驱动器”中创建它。而不是指定的Team Drive。

尝试1

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setSubject('user@mydomain.com');

$service = new Google_Service_Drive($client);

$folderId = '0AIuzzEYPQu9CUk9PVA';
$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'New Test Folder',
    'mimeType' => 'application/vnd.google-apps.folder',
    'supportsAllDrives' => true,
    'parents' => ['0AIuzzEYPQu9CUk9PVA']
));

尝试2

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'New Test Folder',
    'mimeType' => 'application/vnd.google-apps.folder',
    'supportsAllDrives' => true,
    'driveId' => '0AIuzzEYPQu9CUk9PVA'
));

更新尝试3

$fileMetadata = new Google_Service_Drive_DriveFile(array(
    'name' => 'Hello 123',
    'supportsAllDrives' => true,
    'mimeType' => 'application/vnd.google-apps.folder',
    'parents' => ['0AIuzzEYPQu9CUk9PVA']
));

$file = $service->files->create($fileMetadata, array(
      'fields' => 'id'));
    printf("Folder ID: %s\n", $file->id);

尝试3会出现此错误: 致命错误:未捕获Google_Service_Exception:{"错误":{"错误":[{"域":"全球","原因":" notFound"," message":"找不到文件:0AIuzzEYPQu9CUk9PVA。"," locationType":&#34 ;参数"," location":" fileId" }]

我已阅读有关Team Drive和API的所有(有限)documentation,并了解团队驱动器中的文件夹/文件只能有一个父级(团队驱动器的ID),所以我尝试将父变体作为数组和字符串。

文件夹创建正确,位置错误。

如果有人有任何想法,我会很感激帮助。

由于

1 个答案:

答案 0 :(得分:7)

关于如何处理Teamdrives内部文件夹创建的文档不是很清楚,但这是您需要注意的两件事:

1. 'supportsAllDrives' => true,是可选参数的一部分,而不是文件元数据的一部分。 2. parentdriveId都应作为元数据

的一部分包含在内

所以这是一个如何实现这个目标的例子:

$service = new Google_Service_Drive($client);
$parent = "0AA3C8xRqwerLglUk9PVA"; //Teamdrive ID

//Create new folder
$file = new Google_Service_Drive_DriveFile(array(
    'name' => 'Test Folder',
    'mimeType' => 'application/vnd.google-apps.folder',    
    'driveId' => $parent,
    'parents' => array($parent)
));

$optParams = array( 
    'fields' => 'id', 
    'supportsAllDrives' => true,
);

$createdFile = $service->files->create($file, $optParams);
print "Created Folder: ".$createdFile->id;

请注意:您需要客户端库版本2.1.3或更高版本。