I am using Google API Client to upload and convert a file to that user's google drive. How can I automatically share that file with one specific user?
$file = new Google_Service_Drive_DriveFile();
$file->title = $title;
$chunkSizeBytes = 1 * 1024 * 1024;
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $service->files->insert($file, array(
'convert' => true,
));
The webapp is an HTML form that creates a document based on user data. This document needs to later be edited by myself, saved in my google drive, and deleted from the user's google drive.
What is the best/easiest way to achieve this?
To share a file with the Drive API you use Permissions.insert() with the type "user", role of either "reader", "writer", or "commenter", and a value which is their email address. More information about sharing files is available in this developer guide.
Related
I couldn't find out there a PHP tutorial for storing a file in the free bucket of a Google Apps Engine project and retrieving its contents. The idea of this post is to do it step by step assuming the GAE project was correctly created.
1) If you created a GAE project it has been granted a 5Gb of a free Google Cloud Storage bucket. Its name is "YOUR_PROJECT_ID.appspot.com"
https://console.cloud.google.com/storage/browser
2) A Service Account must be created and asgigned to use the SDK.
Steps Here
3) This is the basic PHP code to store a file with a "Hello World" content. This code could be executed from the terminal windows.
<?php
$filename = "tutorial.txt"; // filename in the bucket
$txt_toSave = "Hello Word"; // text content in the file
// lets add code here
?>
php GCStorage_save_example.php
4) This is the basic PHP code to retrieve a file's content from the bucket.
<?php
// lets add code here
echo $txt_fileContent;
?>
php GCStorage_retrieve_example.php
a) if permissions must be granted feel free to add the step
b) if any other step must be done feel free to add it
You can find the PHP code samples for Google Cloud Storage operations in the Official Google Cloud Storage documentation [1].
For instance, an example to store a file in Google Cloud Storage according to the documentation [2] would be:
use Google\Cloud\Storage\StorageClient;
/**
* Upload a file.
*
* #param string $bucketName the name of your Google Cloud bucket.
* #param string $objectName the name of the object.
* #param string $source the path to the file to upload.
*
* #return Psr\Http\Message\StreamInterface
*/
function upload_object($bucketName, $objectName, $source)
{
$storage = new StorageClient();
$file = fopen($source, 'r');
$bucket = $storage->bucket($bucketName);
$object = $bucket->upload($file, [
'name' => $objectName
]);
printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}
You can follow the How-To [3] for retrieving an object from the bucket as well. Note that this is no different than storing/downloading objects from other buckets, as you can specify from which bucket to pull/push from.
[1] https://cloud.google.com/storage/docs/how-to
[2] https://cloud.google.com/storage/docs/uploading-objects
[3] https://cloud.google.com/storage/docs/downloading-objects
I'm able to upload a file to google drive with that code:
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/jpeg');
$data = file_get_contents('a.jpg');
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'multipart'
));
But it will be counted in the quota. How to send it to free storage like google photo ?
If you want to use the Google Photos, you should use the Google Photos APIs upload media.
Note: All media items uploaded to Google Photos through the API are stored in full resolution at original quality. If your uploads exceed 25MB per user, your application should remind the user that these uploads will count towards storage in their Google Account.
Bytes are uploaded to Google using upload requests. If the upload request is successful, an upload token which is in the form of a raw text string, is returned. To create media items, use these tokens in the batchCreate call.
// Create a new upload request
// Specify the filename that will be shown to the user in Google Photos
// and the path to the file that will be uploaded
// When specifying a filename, include the file extension
try {
$uploadToken = $photosLibraryClient->upload(file_get_contents($localFilePath), $filename);
} catch (\GuzzleHttp\Exception\GuzzleException $e) {
// Handle error
}
I'm fairly new to writing in PHP and I've hit a snag while developing a Google Drive connection. I'm trying to create a small widget for a WordPress site wherein users on the site can upload and download files from their Google Drives.
These users are from a closed GSuite Domain and I use a Domain-Wide Service account in order to authenticate and connect to the user's drives.
I am able to connect, retrieve a list of files, and successfully "download" a files contents, though, this download does not actually download a file to the computer, simply returns the contents.
References:
-Uploading: https://developers.google.com/drive/api/v3/manage-uploads
-Downloading: https://developers.google.com/drive/api/v3/manage-downloads
-- I need to place a download button on my page which will allow a user to select a file and download it to their computer without saving it on the server. Currently it just returns the content of the file which I can store in a variable, but I do not know how to have a client request it and download it.
I need an upload button as well but I am working on a solution that I believe will work. I've read many different articles suggesting Ajax, Node, etc...
Ajax:
Calling a PHP function from an HTML form in the same file?
Upload UI:
https://www.htmlgoodies.com/beyond/cms/create-a-file-uploader-in-wordpress.html
In my client initialization file:
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Drive::DRIVE);
$client->setSubject($user_to_impersonate);
$driveService = new Google_Service_Drive($client);
return $driveService;
In the php script that loads the widget on the page:
$drive_connection = getUserGoogleDriveService();
$retrieved_files = array();
$filesList = $drive_connection->files->listFiles();
foreach($filesList->files as $file)
{
array_push($retrieved_files, array(
'filename' => $file->name,
'fileid' => $file->id,
'file' => $file
));
}
$get_specific_file = array_search('example_file_name',
array_column($retrieved_files, 'filename'));
Edit: I added my code thus far. This code successfully lets me store and retrieve files from my array for further use. How would I tie this into a client side UI to upload files to the google "create" function.
I am using Google Drive SDK to upload files by PHP. now I want to get the Link as string so that I can store it in my Database. But I don't have any idea on how to get it.. this is the code in creating the file in google drive using PHP.
$file = new Google_DriveFile();
$file->setTitle( 'new_pdf' );
$file->setMimeType( 'application/pdf' );
$createdFile = $service->files->insert( $file, array(
'data' => $stringContent,
));
You want one of the properties of $createdFile.
The list of properties is at https://developers.google.com/drive/v2/reference/files
You probably want webContentLink, but it depends on how it is you intend to use the URL.
Here is my code to upload a file:
private function addFile(File $file, $folderProject, User $user) {
$fileToUpload = new Google_DriveFile();
$fileToUpload->setTitle($file->getName());
//set mime type
$fileToUpload->setMimeType($file->getMimeType());
//build parent and set id
$parent = new Google_ParentReference();
$parent->setId($folderProject->getId());
//set parent to file
$fileToUpload->setParents(array($parent));
$data = file_get_contents($file->getPath());
$createdFile = $this->service->files->insert($fileToUpload, array(
'data' => $data,
'mimeType' => $file->getMimeType(),
));
}
When I upload for example a docx using this PHP code the file append to be unreadable on the Google Drive website (it shows up the XML structure of the docx) and it is showing up like this in my Google Drive folder:
And when i try to upload a docx directly through Google Drive UI it showing up like this (what i want):
I'm pretty sure that the problem is coming from the fact the Google
Drive UI tries to open the file in a different way because i uploaded
it through my app, but i don't want that :)
(i have the same problem with other kind of files)
I tried to set the parameter 'convert' = true in the array but then i got this error during the upload:
..convert=true&uploadType=multipart&key=AI39si49a86oqv9fhb9yzXp7FCWL-cSqwFiClHZqS3Y3r9Hw8ujtSNlZEWZyFKBp_id7LUyFaZTJ97pMeb0XqHznycK7JJ9o_Q:
(500) Internal Error
Documentation: https://developers.google.com/drive/v2/reference/files/insert
=> But anyway i don't think to convert is the right solution, i just want to be able to see the content as if i uploaded the file through the Google Drive UI
If i open the docx from my Google Drive Sync folders and I edit and save it, I will be able to see it through the Google Drive UI (showing with the W logo)
I also getting the same problem.
But the difference is that , I am uploading pdf and able to view pdf in google drive UI.
I need to automatically convert it to google doc format by api code after adding new pdf.
If I change $mimeType = 'application/vnd.google-apps.document'; then got below error
https://www.googleapis.com/upload/drive/v2/files?convert=true&uploadType=multipart: (400) Bad Request
if I add optional parameter
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => TRUE
));
Then no change , only pdf upload no conversion takes place.
do u have any suggestion , where I need to exactly add for convert parameter ?