Upload the file to a specific folder on Google Drive using PHP and Drive API

Hope it's just ... I want to upload a file directly to a folder. I got the folder id and I have this code that downloads the file perfectly at the root:

<?php
require_once 'get_access.php'; 

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$folder_id = '<folder id>';

$client = new Google_Client();
$client->setClientId('<client_id>');
$client->setClientSecret('<client_secret>');
$client->setRedirectUri('<url>');
$client->setScopes(array('<scope>'));
$client->setAccessToken($access);
$client->setAccessType('offline');
$client->refreshToken($refreshToken);
$service = new Google_DriveService($client);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document 123');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('document-2.txt');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));

echo '<pre>';
var_dump($createdFile);
echo '</pre>';

?>

      

What should I do here to download this file to a specific folder on the user's drive?

thank

+3


source to share


4 answers


I think it's crazy, but Google changed the API again! The ParentReference class is nowGoogle_Service_Drive_ParentReference

So the updated code:



$parent = new Google_Service_Drive_ParentReference();
$parent->setId($folderId);
$file->setParents(array($parent));

      

+7


source


Thanks for the answer. Yes it was a solution and I found it earlier in the API, but it didn't work.

The key is that Google changed the class names, but didn't update the docs. the ParentReference class is nowGoogle_ParentReference()



Similar issue with other docs about Google Drive. So the working code for this is:

$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));

      

+5


source


Assuming that $parentId

contains the target folder id, you should add this code before the insert request:

$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));

      

See the reference guide for details files.insert

:

https://developers.google.com/drive/v2/reference/files/insert

+1


source


Quite late, but I reached this page looking for a solution and since the API changed to V3 the procedure changed as well. I found it after a couple of hours.

In a new way, they made it quite simple.

try this:

$file = new Google_DriveFile();
$file->setName('YourDocument.txt');  // This also changed from Title To Name


$file->setParents(array($parentId));  // This is the Line which sets parent

      

0


source







All Articles