I'm trying to get the file ID of a created file using the google drive API so I can then use that to delete files. Here is the code:
$file = new Google_Service_Drive_DriveFile();
$file->setName($fileName);
$file->setDescription('Volunteer Hours');
$file->setParents(array($folderId));
$data = file_get_contents($filePath);
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
Is there some kind of .id
method where I can say:
$createdFileID = $createdFile.id;
I have looked into the google drive api but wasn't able to find any such method. The reason I want an id for an uploaded file is so I can delete files if I wanted to using that specific id Ultimately, here is the function I'm trying to write:
// Deletes a specific file from a specific folder
function deleteFile($folderName, $fileID) {
}
This way, we are protected and delete the right file if there happens to be files with the same name in a given folder.
I believe your goal as follows.
$fileName
is existing in the specific folder of $folderName
, you want to delete the existing file.In this case, how about the following modification?
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'uploadType' => 'multipart'
));
$createdFileID = $createdFile->getId(); // Added
$createdFileID
.When you want to delete the file using the filename and folder name at function deleteFile($folderName, $fileName) {}
, how about the following sample script?
function deleteFile($folderName, $fileName) {
$client = getClient();
$drive = new Google_Service_Drive($client);
$res1 = $drive->files->listFiles(array("q" => "name='{$folderName}' and trashed=false"));
$folderId = $res1->getFiles()[0]->getId();
$res2 = $drive->files->listFiles(array("q" => "name='{$fileName}' and '{$folderId}' in parents and trashed=false"));
if (count($res2->getFiles()) == 0) {
// When the filename of $fileName is not existing,
// do something
} else {
$fileId = $res2->getFiles()[0]->getId();
$drive->files->delete($fileId);
}
}
$fileName
is existing in the specific folder of $folderName
, the existing file is deleted.When you want to delete the file using the file ID, you can use the following script.
function deleteFile($fileID) {
$client = getClient();
$drive = new Google_Service_Drive($client);
$drive->files->delete($fileID);
}
$folderName
is not required to be used. Because at Google Drive, all files has the unique file ID.