I use this code:
$folder = new Google_Service_Drive_DriveFile([
'name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'
]);
$req = $service->files->create($folder, [
'fields' => 'id'
]);
var_dump($req->id); //NULL
Api version: v3.
Id is always null, but files uploading successfully.
Please try using the suggested code in Creating a folder wherein you need to insert a file with this MIME type and a folder title using array of Strings representing a file's parent folders
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Invoices',
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $driveService->files->create($fileMetadata, array(
'fields' => 'id'));
printf("Folder ID: %s\n", $file->id);
Related
Actually this code is uploading files to normal Gdrive but i need to upload my files into the shared drive can anyone help me. All i need is to Upload my files to to my shared drive. Below is my current code :-
require __DIR__ . '/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
try {
$client = new Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$file = getcwd().'/637fdc0994855.mp4';
$filename = basename($file);
$mimeType = mime_content_type($file);
$fileMetadata = new Drive\DriveFile(array(
'name' => $filename,
'parents' => ['1VBi8C04HBonM6L4CfL-jHWZ0QoQRyrCL']
));
$content = file_get_contents('637fdc0994855.mp4');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
printf("File ID: %s\n", $file->id);
return $file->id;
} catch (Exception $e) {
echo "Error Message: " . $e;
}
}
uploadBasic();
In order to upload the file to the shared drive, please modify as follows.
From:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
To:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id',
'supportsAllDrives' => true // <--- Added
));
Note:
In this case, your client has no permission for writing the shared drive, an error occurs. Please be careful about this.
Reference:
Files: create
I am new to the Google Drive API and have gotten to the point where I have successfully uploaded a file and subsequently am able to list out the file(s) that I uploaded. Something that confused me was that files I uploaded did NOT appear in my Google Drive until I viewed the file via the webContentLink address. Only after viewing the file in a browser via the webContentLink address did the file then magically appear in my Google Drive.
I have seen similar questions on stackoverflow but those seem to be related to the fact that a parent ID was not specified in the upload. I am just curious as to why the file doesn't appear in my Google Drive unless I view the file separately via the webContentLink link. Here is my upload code:
function insertFile($service, $title, $description, $parentId, $mimeType, $filename)
{
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->create($file, array('data' => $data, 'mimeType' => $mimeType));
$Permission = new \Google_Service_Drive_Permission(array(
'type' => 'anyone',
'role' => "reader",
'additionalRoles' => []
));
$service->permissions->create(
$createdFile->getId(), $Permission, array('fields' => 'id'));
return $createdFile;
} catch (Exception $e) {
die("An error occurred: " . $e->getMessage());
}
}
$title="Berkobien Tree";
$description="BerkobienTree upload";
$parentId=null;
$mimeType='application/pdf';
$filename='D:\WWWRoot\babycity.com\httpdocs\BerkobienTree.pdf';
$createdFile = insertFile($service, $title, $description, $parentId, $mimeType, $filename);
it's most likely due to some latence coming from your connection.
When I upload new files, or move files between drives with the API it most often appears instantly, but some other times it takes a few seconds (not more than one minute though). But if you refresh your drive's page emptying cache it should do the trick.
When I create a folder I simply give these informations :
$folderFile = new \Google_Service_Drive_DriveFile([
'name' => $folderName,
'mimeType' => 'application/vnd.google-apps.folder',
'parents' => [$receivingFolderId],
'id' => $service->files->generateIds(['count' => 1, 'space' => 'drive']),
]);
$service->files->create($folderFile, [
'includePermissionsForView' => 'published',
'supportsAllDrives' => true,
]);
and for creating a file / copying a file
// Create new file with seedFile's name and mimeType
$newFile = new \Google_Service_Drive_DriveFile([
'name' => $name,
'mimeType' => $mimeType,
'parents' => [$PARENT_ID],
]);
// Copy the original file data into the newly created file
$service->files->copy($originalFileId, $newFile, [
'supportsAllDrives' => true,
]);
/*
So because I'm using a Team drive and an external drive for this process
I do not have the rights to delete a file from an external drive so I simply remove its parent, and the file is now an 'orphan'.
It is not a suppression of the file !
In my case it fits my needs.
*/
// Remove the original file's parent folder to delete it from his folder
$service->files->update($originalFileId, (new \Google_Service_Drive_DriveFile()), [
'includePermissionsForView' => 'published',
'removeParents' => $originalFileId->getParents(),
'supportsAllDrives' => true,
]);
As you mentioned, you already can create a file, and from your code I can see that it works. So I think your problem just comes from a latence in your internet connection ? Maybe try to set the parent a different way ? I'm just speculating at this point.
I want to add default font family 'Calbri' to my google doc which is generated by PHP API.
I have search more and more but not find any specific solution for my problem.
$parent = 'XXXXX';
$file = new Google_Service_Drive_DriveFile(
array(
'name' => 'XXXX',
'mimeType' => 'application/vnd.google-apps.folder',
'teamDriveId' => $parent,
'parents' => array($parent)
)
);
$filename = 'XXXX';
$file->setName($filename);
$file->setMimeType( 'application/vnd.google-apps.document' );
$result = $this->serviceDrive->files->create($file, array(
'data' => file_get_contents("path/to/file"),
'uploadType' => 'multipart',
));
How can I add default font, page break and table of content on my google doc?
I'm struggling to create a folder within a Team Drive using the Google API PHP Client Library.
I am using a service account and impersonating a user (myself) who is a member of the Team Drive and can list the contents of the drive. However, when I create a folder it always creates it in 'My Drive' rather than the Team Drive specified.
Attempt 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']
));
Attempt 2
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'New Test Folder',
'mimeType' => 'application/vnd.google-apps.folder',
'supportsAllDrives' => true,
'driveId' => '0AIuzzEYPQu9CUk9PVA'
));
UPDATE Attempt 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);
Attempt 3 gives this error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "File not found: 0AIuzzEYPQu9CUk9PVA.", "locationType": "parameter", "location": "fileId" } ]
I have read all the (limited) documentation regarding Team Drive and the API and understand that a folder/file within a Team Drive can only have one parent (The Team Drive's ID) so I have tried variations of the parent as an array and string.
The folder is created correctly, just in the wrong place.
The documentation is not very clear on how to handle the creation of folders inside Teamdrives but this are the two things you need to take note of:
1.'supportsAllDrives' => true, is part of the optional parameters and not part of the file metadata.
2. Both the parent and the driveId should be included as part of the metadata
So here is an example on how to achieve this:
$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;
Please Note: You will need the client library version 2.1.3 or greater.
Here is the parameter, under labels.restricted :
https://developers.google.com/drive/v2/reference/files/insert
But cannot code it in PHP tried almost everything but still getting error from the google drive API.
$file = new Google_Service_Drive_DriveFile();
$file->setTitle(TESTFILE);
$file->setRestricted();
$result = $service->files->insert(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
//
// HERE SHOULD BE THE CODE FOR THE labels.restricted
//
)
);
You have to setRestricted on a Label:
$label = new Google_Service_Drive_DriveFileLabels();
$label->setRestricted(true);
$file->setLabels($label);