【问题标题】:Uploading files to my Google Drive account using PHP使用 PHP 将文件上传到我的 Google Drive 帐户
【发布时间】:2018-03-28 16:07:15
【问题描述】:

我知道有数百篇文章涵盖了这个主题的变体,我花了最后几个小时阅读它们,但我就是无法让它发挥作用。

我想通过 Google Drive SDK 使用 PHP 将文件从我的服务器上传到我的 Google Drive 帐户(我使用的是 v2.2.0)。

脚本执行得很好,它似乎在某处上传,甚至返回一个文件 ID(虽然总是相同),但它没有显示在我的 Google Drive 中,当我尝试查看文件时收到以下消息:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "notFound",
    "message": "File not found: <FILE_ID>.",
    "locationType": "parameter",
    "location": "fileId"
   }
  ],
  "code": 404,
  "message": "File not found: <FILE_ID>."
 }
}

我已经设置了一个服务帐户并下载了 JSON 凭据。我的目标是创建一个用于上传存储在我的服务器上的文件的功能,因此我不需要 oAuth 同意屏幕。

这是目前为止的测试代码:

<?php

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

    putenv('GOOGLE_APPLICATION_CREDENTIALS=../../../keys/MyProject-xxxxxxxxxxxx.json');

    $client = new Google_Client();
    $client->addScope(Google_Service_Drive::DRIVE);
    $client->useApplicationDefaultCredentials();
    $client->setApplicationName("MyApplication");
    $client->setScopes(['https://www.googleapis.com/auth/drive.file']);

    $file = new Google_Service_Drive_DriveFile();
    $file->setName(uniqid().'.jpg');
    $file->setDescription('A test document');
    $file->setMimeType('image/jpeg');

    $data = file_get_contents('cat.jpg');

    $service = new Google_Service_Drive($client);

    $createdFile = $service->files->create($file, array(
    'data' => $data,
    'mimeType' => 'image/jpeg',
    'uploadType' => 'multipart'));

    echo("<a href='https://www.googleapis.com/drive/v3/files/".$createdFile->id."?key=<MY_API_KEY>&alt=media' target='_blank'>Download</a>");

【问题讨论】:

    标签: php google-drive-api uploading


    【解决方案1】:

    解决了!

    您需要在 Google 云端硬盘中创建一个文件夹,然后将服务帐户电子邮件地址添加到可以添加和编辑的人员列表中。

    然后你需要在你的代码中指定文件夹id:

    $file->setParents(array("0B_xxxxxxxxxxxxxxxxxxxxxxxxx"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      相关资源
      最近更新 更多