【问题标题】:Upload file into particular folder on Google Drive using PHP and Drive API使用 PHP 和 Drive API 将文件上传到 Google Drive 上的特定文件夹
【发布时间】:2013-01-28 16:16:14
【问题描述】:

希望这是一个简单的...我想将文件直接上传到文件夹中。我得到了文件夹 ID,并且我有这段代码可以完美地在根目录中上传文件:

<?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>';

?>

我应该在这里做什么才能将此文件上传到用户驱动器上的特定文件夹中?

谢谢

【问题讨论】:

    标签: php google-drive-api


    【解决方案1】:

    我想这很疯狂,但 Google 又一次更改了 API! ParentReference 类现在是Google_Service_Drive_ParentReference

    所以更新后的代码是:

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

    【讨论】:

      【解决方案2】:

      感谢您的回答。是的,这就是解决方案,我之前在 API 中找到了它,但它没有用。

      关键是谷歌更改了类名,但没有更新文档。 ParentReference 类现在是Google_ParentReference()

      关于 Google Drive 的其他文档也存在类似问题。所以,这个的工作代码是:

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

      【讨论】:

        【解决方案3】:

        很晚了,但我到了这个页面寻找解决方案,并且由于 API 更改为 V3,程序也发生了变化。几个小时后,我找到了它。

        以新的方式,他们让它变得非常简单。

        试试这个:

        $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
        

        【讨论】:

          【解决方案4】:

          假设$parentId包含目标文件夹的id,你应该在插入请求之前添加这段代码:

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

          有关详细信息,请查看files.insert 参考指南:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-01-16
            • 1970-01-01
            • 1970-01-01
            • 2019-07-26
            • 1970-01-01
            • 2020-03-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多