问题
I have several scripts in php to create a folder and upload a file to the desired folder, but I can't seem to be able to create new folders, new subfolders or create another function to do this process. Do i have to use a parent/children specific procedure? Here's the functional code I use to create a folder:
function getFolderExistsCreate($service, $folderName, $folderDesc) {
// Lista el root de drive
$files = $service->files->listFiles();
$found = false;
// Checa los folders en ciclo
foreach ($files['items'] as $item) {
if ($item['title'] == $folderName) {
$found = true;
return $item['id'];
break;
}
}
// Lo crea si no lo encontro
if ($found == false) {
$folder = new Google_Service_Drive_DriveFile();
//Poner los settings del folder
$folder->setTitle($folderName);
if(!empty($folderDesc))
$folder->setDescription($folderDesc);
$folder->setMimeType('application/vnd.google-apps.folder');
//Try de crear el folder
try {
$createdFile = $service->files->insert($folder, array(
'mimeType' => 'application/vnd.google-apps.folder',
));
// Regresa el nuevo id del folder
return $createdFile->id;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
}
Help please, thanks!
回答1:
To create a subfolder to a particular folder, you should specify the correct ID in the parents
property of the file.
"parents": [{"id":"0ADK06pfg"}]
Check this page for more information
Hope that helps!
回答2:
You need to set the parent id of the folder you want to place it in.
code from files.insert
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
Eastest way to get the folder id is to do a files.list use the q search option to search for folders only mimeType = 'application/vnd.google-apps.folder'
then you can find the folder you want to place you new folder or file into.
回答3:
It seems that the class Google_Service_Drive_ParentReference() doesn't work anymore.. Use this:
$fileMetadata = new Google_Service_Drive_DriveFile(array(
//Set the Random Filename
'name' => $rdmName,
//Set the Parent Folder
'parents' => array('0BzaRxkCDivjIM1pUYU1SLWVxOGM')
));
try{
$newFile = $drive_service->files->create(
$fileMetadata,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/pdf',
'uploadType' => 'media'
)
);
} catch(Exception $e){
echo 'An error ocurred : ' . $e->getMessage();
}
来源:https://stackoverflow.com/questions/30087112/dynamically-create-folders-and-subfolders