首页 > 解决方案 > 如何使用 php Google Drive API 在 Google Drive 上上传文件

问题描述

我想使用 php API 在我的 Google Drive 中添加一个文件。我在谷歌控制台和谷歌管理员中正确设置了服务帐户权限。我的代码如下:

$client = new Google_Client();
$client->setAuthConfig('path.json');
$client->addScope('https://www.googleapis.com/auth/drive');

$service = new Google_Service_Drive($client);

//Insert a file
$fileMetadata = new Google_Service_Drive_DriveFile(array('name' => 'test.txt'));
$content = file_get_contents('test.txt');
$file = $service->files->create($fileMetadata, array(    'data' => $content, 'mimeType' => 'text/plain', 'uploadType' => 'multipart', 'fields' => 'id'));
print($file->id);

它返回 id : 1otqEi5qaJ8SDjcPMIFOWtMQVPXZKlaSb 但是我的驱动器上不存在该文档...

感谢帮助...

标签: phpgoogle-apigoogle-drive-apigoogle-api-php-clientservice-accounts

解决方案


服务帐户不是您。服务帐户有自己的 google drive 帐户。该文件正在上传到其 google drive 帐户。

如果您希望它上传到您的 google drive 帐户,请使用服务帐户电子邮件地址添加与它共享您的 google drive 帐户中的目录。然后获取该文件夹的文件 ID/驱动器 ID,并在您上传文件时将其设置为文件元数据中的父级,它将上传到您的驱动器帐户而不是服务帐户。

请记住让服务帐户在上传该文件后授予您对该文件的权限,该文件将归服务帐户所有。


推荐阅读