How to upload files to Google drive Shared drive folder? - php

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

Related

How to overwrtite an file on Google Drive with php?

Anyone who has had anything to do with google files, can you tell me how to overwrite a file?
Now I use this function but, even if the names are the same, it creates another one.
function uploadFile($fileName, $folderId, $file) {
$service = getGoogleDriveService();
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $fileName,
'parents' => array($folderId),
));
try {
$newFile = $service->files->create(
$fileMetadata,
array(
'data' => file_get_contents($file),
'mimeType' => mime_content_type($file),
'uploadType' => 'multipart',
)
);
return $newFile->id;
} catch (Exception $e) {
return 'An error ocurred : ' . $e->getMessage();
}
}

Can't load properly google-api-php-client-2.2.0 library in Drupal 7

i created new module "googleapi.module" from there i'm trying to load the google api library to create some file in google drive, but i receive an error:
[message:protected] => file does not exist
/home/main/public_html/backoffice/sites/all/modules/main/googleapi/library/google-api-php-client-2.2.0/src/Google/Client.php
I think it's something to do with drupal paths, because i have a simple index.php file that works perfect and loading the library...
Here is the drupal code:
function googleapi_permission() {
return array(
'access googleapi' => array('title' => t('Access Google API')),
);
}
function googleapi_menu() {
$items = array();
$items['googleapi'] = array(
'title' => t('Google API'),
'page callback' => 'googleapi_main',
'access callback' => 'user_access',
'access arguments' => array('access googleapi'),
'type' => MENU_CALLBACK,
);
return $items;
}
function googleapi_main() {
$path = drupal_get_path('module', 'googleapi');
require_once "./$path/library/google-api-php-client-2.2.0/vendor/autoload.php";
$config_file = 'Zebraclick_Drive_API-891f9b06f8ae.json';
$folderId = '0B-XFow04K90UPTRYRFRsZk5HdDA';
$filename = 'text.'.time();
$filemime = 'text/plain';
try {
$data = 'server test';
$client = new Google_Client();
$scopes = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.file'];
$client->setAuthConfig($config_file);
$client->setScopes($scopes);
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile(array(
'name' => $filename,
'parents' => array($folderId),
'mimeType' => 'application/vnd.google-apps.document'
));
$file->setName($filename);
$result = $service->files->create($file, array(
'data' => $data,
'mimeType' => $filemime,
'uploadType' => 'multipart'
));
$fileId = $result['id'];
$publicOriginallink = "https://drive.google.com/open?id=".$fileId;
$type = 'anyone';
$role = 'writer';
$msg = 'File saved. Please check the folder in Drive.';
}
catch(Exception $e) {
print_r($e);
$msg = $e->getMessage() . '<br />';
$msg .= 'Error occurred. Please try again. If this happens again, please contact the developer.';
return $msg;
}
}
try with
require_once "$path/library/google-api-php-client-2.2.0/vendor/autoload.php";
or
require_once __DIR__."/library/google-api-php-client-2.2.0/vendor/autoload.php";
If it's not efficient , maybe autoload.php needs namespace definition

Why folder id is null when I try to create folder?

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);

How do I set labels.restricted / want to restrict the file from Downloading in Google Drive

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);

phpqrcode + save cached file to Amazon instead of folder on server

What I do now is creating a QR code image (PNG) and save a copy of it in a folder on the root of my server. Now I would like to save this image not on my server but on my amazon bucket.
I know how I can save a file on amazon but I can't figure out how to make this work together.
This is my original code for saving it in a root folder on my server:
$fileName = $quiz_url . '.png';
$pngAbsoluteFilePath = APPLICATION_PATH . '/../public/qrcodecaches/' . $fileName;
$urlRelativeFilePath = '/qrcodecaches/' . $fileName;
// generating
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png('http://mysitelink.com/s/'.$quiz_url, $pngAbsoluteFilePath, 'L', 4, 2);
}
And this is how I save a file on Amazon:
$bucket = 'mybucket';
$map = 'qrcodecaches';
$client = S3Client::factory(array(
'key' => 'mykey',
'secret' => 'mysecret',
));
$fileName = $quiz_url . '.png';
$keyname = $map . '/' . $fileName;
try {
$client->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'Body' => fopen('/path/to/file', 'r'),
'ACL' => 'public-read',
));
} catch (S3Exception $e) {
echo "There was an error uploading the file.\n";
}
But what do I need to save in the 'Body' tag? Can somebody help me with this?
You can create the image file passing a temporary file name like this:
$pngAbsoluteFilePath = tempnam(sys_get_temp_dir(), 'qr_code_');
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png('http://mysitelink.com/s/'.$quiz_url, $pngAbsoluteFilePath, 'L', 4, 2);
}
then all you need to do is to get that file contents and pass it in to the Body of the object in bucket:
try {
$client->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'Body' => file_get_contents($pngAbsoluteFilePath), // like this
'ACL' => 'public-read'
));
}
catch (S3Exception $e) {
echo "There was an error uploading the file.\n";
}
After you're done - in case of successful upload - you can delete the temporary file. It is not necessary, however recommended because it will fill your /tmp with QR images until your server is restarted:
if ( empty($e) ) {
unlink($pngAbsoluteFilePath);
}
This worked well for me.
Amazon S3Client documentation suggests that you can poll to check that the upload was successful.
$client->waitUntilObjectExists(array(
'Bucket' => $bucket,
'Key' => $keyname
));
Alternatively if you're already writing the file to disk on your server you can supply S3Client with the path to that file and let it handle the filestream itself.
try {
$client->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => '/path/to/file',
'ACL' => 'public-read'
));
} catch (S3Exception $e) {
echo "There was an error uploading the file.\n";
}
Source: http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html#_putObject

Categories