【发布时间】:2015-06-12 21:18:42
【问题描述】:
我已经挣扎了好一阵子了;通过 Google 驱动 PHP API,我可以创建一个子文件夹或将文件添加到现有文件夹中,但是尝试在子文件夹中放置另一个子文件夹或文件似乎是不可能的。
经过研究,我遇到了 Children 功能,但不明白如何应用它,即使在查看了此页面上的 Google 文档后:[https://developers.google.com/drive/v2/reference/children/insert][1]
我用来将图像添加到文件夹的代码是:
//Insert a file into client specific folder
$file = new Google_Service_Drive_DriveFile();
$file->setTitle(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$data = file_get_contents('a.jpg');
$parent = new Google_Service_Drive_ParentReference(); //previously Google_ParentReference
$parent->setId($folderid); //$folderid = determined folder id
$file->setParents(array($parent));
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart'
));
如何继续将此图像上传到 ID 已确定的特定子文件夹?
更新: 这是我尝试的组合代码:
- 使用existing_folder 的父级创建new_sub_folder1,并存储返回的ID
- 使用第 1 步中存储的 ID 创建 new_file1 和 new_sub_folder1 的父级
$service = new Google_Service_Drive($client);
//create sub folder
$folder = new Google_Service_Drive_DriveFile();
//Setup the folder to create
$folder->setTitle('new_sub_folder1');
$folder->setMimeType('application/vnd.google-apps.folder');
//Create the Folder within existing_folder
$parentid = '0B40CySVsd_Jaa1BzVUQwLUFyODA';
//Set the Parent Folder to existing_folder
$parent = new Google_Service_Drive_ParentReference(); //previously Google_ParentReference
$parent->setId($parentid);
$folder->setParents(array($parent));
//now create the client specific folder new_sub_folder
try {
$createdFile = $service->files->insert($folder, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
// Return the created folder's id
$subfolderid = $createdFile->id;
echo $subfolderid;
return $createdFile->id;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
//Insert a file into client specific folder new_sub_folder
$file = new Google_Service_Drive_DriveFile();
$file->setTitle(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$data = file_get_contents('a.jpg');
//Set the Parent Folder to new_sub_folder
$parent = new Google_Service_Drive_ParentReference(); //previously Google_ParentReference
$parent->setId($subfolderid);
$file->setParents(array($parent));
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart'
));
print_r($createdFile);
但是只创建了new_sub_folder1,并没有将文件添加到这个文件夹中。
更新: 该代码不会在任何地方添加图像。如果我应用相同的方法将 .jpg 通过其 ID 添加到现有文件夹,则没有问题。只要我使用 sub_folder_1 的 ID,什么都不会创建 - 相同的方法,不同的 ID。
【问题讨论】:
-
您能否再解释一下子文件夹的含义以及什么不起作用。你的代码对我来说看起来不错
-
我能够:existing_folder -> new_file1、new_file2 等以及:existing_folder -> new_subfolder1、new_subfolder2 等。我不能:existing_folder -> new_sub_folder1->new_file1、new_file2 等. 这就是我想要实现的;将文件添加到子文件夹
标签: php file-upload google-drive-api google-api-php-client subdirectory