首页 > 解决方案 > 服务帐户 - 上传的 PPTX 文件未显示在我的 Google 云端硬盘中

问题描述

当使用服务帐户将文件上传到我的谷歌驱动器时,这应该是一个奇怪的时刻,而谷歌驱动器中没有显示。

我在某处读到服务帐户文件不会显示在我的谷歌驱动器中。那么服务帐户的意义是什么?以及如何通过服务帐户在我的 google drive 帐户中上传文件?

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/vendor/autoload.php';


putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials.json');

$client = new Google\Client();

if (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
  // use the application default credentials
  $client->useApplicationDefaultCredentials();
} else {
  echo missingServiceAccountDetailsWarning();
  return;
}

$client->setApplicationName("Client_Library_Examples");
//$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->addScope("https://www.googleapis.com/auth/drive");

$service = new Google_Service_Drive($client);


//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName('test-1.pptx');
$file->setDescription('A test document');
$file->setMimeType('application/vnd.openxmlformats-officedocument.presentationml.presentation');

$data = file_get_contents('test-1.pptx');

$createdFile = $service->files->create($file, array(
      'data' => $data,
      'mimeType' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'uploadType' => 'multipart'
    ));

echo '<pre>';

var_dump($createdFile);

// Print the names and IDs for up to 10 files.
$optParams = array(
  'pageSize' => 10,
  'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);

var_dump($results);

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

解决方案


服务帐户是虚拟用户。他们有自己的谷歌驱动器帐户。默认情况下,当您上传文件时,它将转到服务帐户 Google 驱动器帐户。

现在,如果您想将文件上传到您的个人驱动器帐户。您可以做的是与服务帐户共享您的谷歌驱动器帐户上的一个文件夹,基本上使用服务帐户电子邮件地址,其中包含一个@,并通过网络应用程序与它共享目录,就像您与任何其他用户一样。

现在服务帐户将立即可以访问它,这称为预授权。通过预授权服务帐户,用户无需交互即可访问该文件夹。

您似乎正在尝试创建一个新文件,您需要做的就是在上传之前在元数据中设置文件的父文件夹。

 $file->setParents('FolderIdFromYourDrive');

如果您想找出文件夹是什么,请先在服务帐户驱动器帐户上执行 file.list,或者您可以查看 url 栏中的顶部。

如果您的应用程序有一些需要访问的静态数据,服务帐户就很好。这可以通过将文件放在驱动器上然后授予服务帐户访问这些文件的权限来完成。服务帐户很棒,因为它们是预先授权的,您不需要同意屏幕来访问私人用户数据。

您还可以将文件上传到服务帐户驱动器帐户并与您的个人谷歌帐户共享,您将可以通过这种方式访问​​。


推荐阅读