Google Drive API v3 - upload files in PHP

I am trying to understand the download stream for Google Drive API v3 using PHP. Using API v2 to download file I:

  • File metadata retrieved
  • I used the downloadUrl parameter to get a direct link to the file, attached the oAuth token to it and made a GET request.

Using API v3 seems deprecated, and according to docs, you call files->get() on the disk service with the array parameter "alt" => "media" to get the file, not the metadata.

And their example:

 $fileId = '0BwwA4oUTeiV1UVNwOHItT0xfa2M'; $content = $driveService->files->get($fileId, array( 'alt' => 'media' )); 

I had problems understanding how this works, and broke through the code, but it did not give more information.

When you call get() , what actually goes to $content in the example? Is it the contents of the file (in this case, it seems problematic when working with large files - you probably will go out of memory ?!) or is it some kind of stream link that I can call fopen on? How to save this file to disk?

There is no detailed information in the documentation about what happens when you make this API call, does it just say that it is downloading the file?

+5
source share
1 answer

I realized this after a bit of experimentation.

When you call the get() method with the alt=>media parameter, as indicated in the docs, you get a basic HTTP response that is the object of the Guzzle response (as apparently the client library uses Guzzle for it that underlies the transport).

From there, you can call any Guzzle response method, for example $response->getStatusCode() , or you can get a stream of the actual contents of the file.

It would be helpful if they fixed it somewhere!

EDIT: Here is an example if someone else is stuck on how to save a file.

 <?php date_default_timezone_set("Europe/London"); require_once 'vendor/autoload.php'; // I'm using a service account, use whatever Google auth flow for your type of account. putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service/account/key.json'); $client = new Google_Client(); $client->addScope(Google_Service_Drive::DRIVE); $client->useApplicationDefaultCredentials(); $service = new Google_Service_Drive($client); $fileId = "0Bxxxxxxxxxxxxxxxxxxxx"; // Google File ID $content = $service->files->get($fileId, array("alt" => "media")); // Open file handle for output. $outHandle = fopen("/path/to/destination", "w+"); // Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle. while (!$content->getBody()->eof()) { fwrite($outHandle, $content->getBody()->read(1024)); } // Close output file handle. fclose($outHandle); echo "Done.\n" ?> 
+11
source

Source: https://habr.com/ru/post/1258171/


All Articles