![](/img/trans.png)
[英]Uploading file to specific folder using google drive api with PHP
[英]Send file to Google Drive from CLI to specific folder using public API key
我正在嘗試使用公共API密鑰從CLI PHP腳本將測試文件發送到我的Google Drive帳戶中的特定文件夾。 我已經生成了密鑰,並在Google開發人員控制台中設置了IP地址。
這是我目前所在的位置:
<?php
if (strtolower(PHP_SAPI) !== 'cli')
{
throw new Exception("Run this from CLI only");
}
$autoloader_path = '.' . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR;
$autoloader_file = realpath($autoloader_path . 'autoload.php');
if (!file_exists($autoloader_file))
{
throw new Exception("Autoloader file not found");
}
require_once $autoloader_file;
if (!class_exists('\Composer\Autoload\ClassLoader', true))
{
throw new Exception("Composer autoloader failed to load");
}
$client = new Google_Client();
$client->setDeveloperKey('my-public-api-key');
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile($client);
$d = array(
'data' => file_get_contents("test.txt"),
'mimeType' => 'text/plain',
'uploadType' => 'media'
);
$result = $service->files->insert($file, $d);
var_dump($result);
我收到“需要登錄”錯誤:
$ php backup.php
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=media&key=**<my key>**: (401) Login Required' in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php:79
Stack trace:
#0 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Client.php(556): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /home/raspi/gdrive/vendor/google/apiclient/src/Google/Service/Drive.php(1760): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /home/raspi/gdrive/backup.php(37): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 {main}
thr in /home/raspi/gdrive/vendor/google/apiclient/src/Google/Http/REST.php on line 79
那么,如何使用公共API密鑰發送文件或需要使用OAuth? 我已經用Google搜索過,但是只發現OAuth文件發送示例。
composer.json
:
{
"name": "raspi/gdrive",
"description": "Gdrive",
"license": "BSD",
"require": {
"php": ">=5.4",
"google/apiclient": "1.0.*@beta"
}
}
如果未通過OAuth 2.0進行身份驗證,則無法訪問或對雲端硬盤帳戶進行任何更改。 OAuth僅授予您的應用程序訪問和更新帳戶的權限。 可以在以下鏈接中找到有關OAuth流程的更多信息: https : //developers.google.com/drive/web/quickstart/quickstart-php
以發送文件為例,如果文件存儲在計算機中,則您將依賴Drive API下“文件”資源的“插入”方法。 使用parents []屬性來指定要將項目保存到的文件夾的ID。 檢查此鏈接以獲取php中的示例: https : //developers.google.com/drive/v2/reference/files/insert
最后,如果要在驅動器帳戶中移動文件,則必須使用相同資源(文件)的“復制”方法。 您將必須提供項目ID作為復制項目的參數,並提供要創建副本的文件夾的parentId。 這是參考: https : //developers.google.com/drive/v2/reference/files/copy
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.