我不知道我是否正确理解了您的问题,但为了以编程方式在 Google Drive 的根目录中创建一个文件夹,您可能需要使用以下代码。在 Google Drive 中,文件夹是一种特殊的文件类型(application/vnd.google-apps.folder
即),有关详细信息,请参阅其 API 文档。
$client = new Google_Client();
// set various parameters, including name, key and secret
$service = new Google_Service_Drive($client);
$about = $service->about->get();
$rootID = $about->getRootFolderId();
createFolderIfNotExists($service, $rootID, "stackfolder");
// creates a folder in the given rootID or returns the ID if it already exists
function createFolderIfNotExists($service, $rootID, $foldername) {
$search = "title='{$foldername}' AND '{$rootID}' in parents AND mimeType = 'application/vnd.google-apps.folder' AND trashed != true";
$parameters = array("q" => $search);
$files = $service->files->listFiles($parameters);
if (!empty($files["items"])) {
$folderID = $files["items"][0]->getId(); // the first element
} else {
// create a folder under root
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($foldername);
// To create new folder, we need to set the mime type
$file->setMimeType('application/vnd.google-apps.folder');
// set parent folder
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($rootID);
$file->setParents(array($parent));
$folder = $service->files->insert($file);
$folderID = $folder->getId();
}
return $folderID;
}