如何浏览项目谷歌驱动器中的文件

时间:2015-05-29 14:23:47

标签: php google-drive-api

我在谷歌控制台中创建了具有服务类型凭据的项目。我已经下载了p12密钥文件,然后编写了用于插入文件的示例代码来测试它:

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";

$scopes = array('https://www.googleapis.com/auth/drive');
$accountEmail = 'SECRET';
$accountP12FilePath = './key.p12';


$key = file_get_contents($accountP12FilePath);
$auth = new Google_AssertionCredentials($accountEmail, $scopes, $key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
$service = new Google_DriveService($client);

$file = new Google_DriveFile();
$file->setTitle('Test Title');
$file->setDescription('test description');
$parent = new Google_ParentReference();
$file->setParents(array($parent));


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

var_dump($createdFile);
?>

它使用许多网址转储Google_DriveFile对象。其中一些,如'downloadUrl',返回401 Unauthorized错误。当我尝试'alternateLink'时,它显示了谷歌驱动器页面,其中包含我需要访问的信息,以及用于请求访问和切换帐户的按钮。

它还说我当前登录了我的帐户,这用于创建项目,这在谷歌控制台页面上的项目的权限页面上可见。

如何访问属于我在脚本中使用的项目的驱动器?

1 个答案:

答案 0 :(得分:0)

终于找到了解决方案,它缺少文件权限。值得注意的是,将权限对象传递给$ file对象(在插入之前)并不起作用。我必须通过将已创建的文件ID和权限对象传递给$ service-&gt; permissions-&gt;插入方法来插入权限,就像这样:

$permission = new Google_Permission();
$permission->setValue('PERSONAL.ACCOUNT@gmail.com');
$permission->setType('user');
$permission->setRole('writer');
$service->permissions->insert($createdFile->getId(), $permission);

我仍然无法实际编辑此文件。当我用URL打开文件时

$createdFile->getAlternateLink();

然后我不得不用谷歌文档重新打开该文件。将文件复制到我的个人帐户,然后我只能编辑文件的副本,而不能只编辑基本文件。

我不知道是否有办法让这些文件真正可编辑,但我转移到了Dropbox,如google drive API及其文档SUX