[英]Uploading files to my Google Drive account using PHP
我知道有數百篇文章涉及該主題的變體,而我已經花了最后幾個小時閱讀它們,但是我無法使它正常工作。
我想通過Google Drive SDK使用PHP從服務器將文件上傳到我的Google Drive帳戶(我正在使用v2.2.0)。
該腳本執行正常,似乎正在某個地方上傳,甚至返回了一個文件ID(盡管始終相同),但是它沒有顯示在我的Google雲端硬盤中,當我嘗試查看該文件時會收到以下消息:
{
"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>");
解決了!
您需要在Google雲端硬盤中創建一個文件夾,然后將服務帳戶的電子郵件地址添加到可以添加和編輯的人員列表中。
然后,您需要在代碼中指定文件夾ID:
$file->setParents(array("0B_xxxxxxxxxxxxxxxxxxxxxxxxx"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.