The problem is that I get log that file has been created and uploaded, but nothing actually changes, I'm novice in working with google api, so I can't figure out what I do wrong.
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig('./credentials.json');
$client->setClientId('2445617429-6k99ikago0s0jdh5q5k3o37de6lqtsd3.apps.googleusercontent.com');
$client->setClientSecret('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');
$service = new Google_Service_Drive($client);
//counting amount of files in folder, there is no real reason in doing that
//it is just a test of connecting
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$options = [
'q' => "'" . $folder_id . "' in parents",
'fields' => 'files(id, name)'
];
//printing result
$results = $service->files->listFiles($options);
echo count($results->getFiles());
//trying to add file
$data = file_get_contents("../test.jpg");
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid(). '.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$new_file = $service->files->create($file, [
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart',
]);
print_r($new_file);
}
What I get after print_r:
Google\Service\Drive\DriveFile Object ( [collection_key:protected] => spaces [appProperties] => [capabilitiesType:protected] => Google\Service\Drive\DriveFileCapabilities [capabilitiesDataType:protected] => [contentHintsType:protected] => Google\Service\Drive\DriveFileContentHints [contentHintsDataType:protected] => [contentRestrictionsType:protected] => Google\Service\Drive\ContentRestriction [contentRestrictionsDataType:protected] => array [copyRequiresWriterPermission] => [createdTime] => [description] => [driveId] => [explicitlyTrashed] => [exportLinks] => [fileExtension] => [folderColorRgb] => [fullFileExtension] => [hasAugmentedPermissions] => [hasThumbnail] => [headRevisionId] => [iconLink] => [id] => 15ZN1wdlSfbXauvuGVnO1nTMC3fbQWMNF [imageMediaMetadataType:protected] => Google\Service\Drive\DriveFileImageMediaMetadata [imageMediaMetadataDataType:protected] => [isAppAuthorized] => [kind] => drive#file [labelInfoType:protected] => Google\Service\Drive\DriveFileLabelInfo [labelInfoDataType:protected] => [lastModifyingUserType:protected] => Google\Service\Drive\User [lastModifyingUserDataType:protected] => [linkShareMetadataType:protected] => Google\Service\Drive\DriveFileLinkShareMetadata [linkShareMetadataDataType:protected] => [md5Checksum] => [mimeType] => image/jpeg [modifiedByMe] => [modifiedByMeTime] => [modifiedTime] => [name] => 6360554211ca3.jpg [originalFilename] => [ownedByMe] => [ownersType:protected] => Google\Service\Drive\User [ownersDataType:protected] => array [parents] => [permissionIds] => [permissionsType:protected] => Google\Service\Drive\Permission [permissionsDataType:protected] => array [properties] => [quotaBytesUsed] => [resourceKey] => [sha1Checksum] => [sha256Checksum] => [shared] => [sharedWithMeTime] => [sharingUserType:protected] => Google\Service\Drive\User [sharingUserDataType:protected] => [shortcutDetailsType:protected] => Google\Service\Drive\DriveFileShortcutDetails [shortcutDetailsDataType:protected] => [size] => [spaces] => [starred] => [teamDriveId] => [thumbnailLink] => [thumbnailVersion] => [trashed] => [trashedTime] => [trashingUserType:protected] => Google\Service\Drive\User [trashingUserDataType:protected] => [version] => [videoMediaMetadataType:protected] => Google\Service\Drive\DriveFileVideoMediaMetadata [videoMediaMetadataDataType:protected] => [viewedByMe] => [viewedByMeTime] => [viewersCanCopyContent] => [webContentLink] => [webViewLink] => [writersCanShare] => [internal_gapi_mappings:protected] => Array ( ) [modelData:protected] => Array ( ) [processed:protected] => Array ( ) )
CodePudding user response:
This is my standard upload code for uploading.
Try removing 'uploadType' => 'multipart',
in your code.
I also cant see you setting the folder id when you upload your file which means its going to root directory.
// Upload a file to the users Google Drive account
try{
$filePath = "image.png";
$folder_id = '1eQtNOJjlA2CalZYb90bEs34IaP6v9ZHM';
$fileMetadata = new Drive\DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
Remember if you are using a service account, files are uploaded to the service accounts drive account unless you add the folder you want to upload the file to.
files list
// Print the next 10 events on the user's drive account.
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
CodePudding user response:
Using the code which was suggested to me, this is full solution. (Thanks everybody who helped me)
<?php
include '../vendor/autoload.php';
function handleGoogleDrive($file)
{
//connecting to google drive
$client = new \Google_Client();
$client->setClientId('YOUR ID IN SECRET FILE');
$client->setClientSecret(YOUR SECRET IN JSON FILE);
$client->setRedirectUri(YOUR REDIRECT URI);
//you should register redirect uri
$client->setApplicationName('Somesite');
$client->setScopes([\Google_Service_Drive::DRIVE]);
$client->setAuthConfig('./credentials.json');
$service = new Google_Service_Drive($client);
try{
$filePath = "../test.jpg";
$folder_id = 'YOUR FOLDER ID';
$fileMetadata = new Google_Service_Drive_DriveFile();
$fileMetadata->setName("image.png");
$fileMetadata->setMimeType('image/png');
$fileMetadata->setParents(array($folder_id));
$content = file_get_contents($filePath);
$mimeType=mime_content_type($filePath);
$request = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'fields' => 'id'));
printf("File ID: %s\n", $request->id);
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
try{
$optParams = array(
'pageSize' => 10,
'fields' => 'files(id,name,mimeType)'
);
$results = $service->files->listFiles($optParams);
$files = $results->getFiles();
if (empty($files)) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($files as $file) {
$id = $file->id;
printf("%s - (%s) - (%s)\n", $file->getId(), $file->getName(), $file->getMimeType());
}
}
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo 'Message: ' .$e->getMessage();
}
}