简体   繁体   中英

Upload file into particular folder on Google Drive using PHP and Drive API

Hope this is an easy one... I want to upload file directly into a folder. I got folder ID and I have this code that uploads file in the root perfectly:

<?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 in order to upload this file into particular folder on user's drive?

Thanks

I guess this is crazy, but Google has changed the API yet again! The ParentReference class is now Google_Service_Drive_ParentReference

So the updated code is:

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

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

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

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

Assuming $parentId contains the id of the target folder, you should add this code before the insert request:

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

For more details, check the files.insert reference guide:

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

Quite late, but I reached this page searching for the solution, and since the API changed to V3, the procedure also changed. After couple of hours i found it.

In the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM