簡體   English   中英

使用PHP和Drive API將文件上傳到Google雲端硬盤上的特定文件夾

[英]Upload file into particular folder on Google Drive using PHP and Drive API

希望這是一個簡單的...我想直接將文件上傳到文件夾中。 我有文件夾ID,我有這個代碼完全上傳根文件:

<?php
require_once 'get_access.php'; 

require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$folder_id = '<folder id>';

$client = new Google_Client();
$client->setClientId('<client_id>');
$client->setClientSecret('<client_secret>');
$client->setRedirectUri('<url>');
$client->setScopes(array('<scope>'));
$client->setAccessToken($access);
$client->setAccessType('offline');
$client->refreshToken($refreshToken);
$service = new Google_DriveService($client);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document 123');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('document-2.txt');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' => 'text/plain',
    ));

echo '<pre>';
var_dump($createdFile);
echo '</pre>';

?>

為了將此文件上傳到用戶驅動器上的特定文件夾,我該怎么做?

謝謝

我猜這很瘋狂,但谷歌又改變了API! ParentReference類現在是Google_Service_Drive_ParentReference

所以更新的代碼是:

$parent = new Google_Service_Drive_ParentReference();
$parent->setId($folderId);
$file->setParents(array($parent));

感謝您的回答。 是的,這是解決方案,我之前在API中找到了它,但它沒有用。

關鍵是谷歌改變了類名,但沒有更新文檔。 ParentReference類現在是Google_ParentReference()

與其他有關Google雲端硬盤的文檔存在類似問題。 所以,這個的工作代碼是:

$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));

假設$parentId包含目標文件夾的id,您應該在插入請求之前添加此代碼:

$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));

有關更多詳細信息,請查看files.insert參考指南:

https://developers.google.com/drive/v2/reference/files/insert

很晚了,但是我到達了這個頁面尋找解決方案,並且由於API改為V3,程序也發生了變化。 幾個小時后我發現了它。

以新的方式,他們使它變得非常簡單。

嘗試這個:

$file = new Google_DriveFile();
$file->setName('YourDocument.txt');  // This also changed from Title To Name


$file->setParents(array($parentId));  // This is the Line which sets parent

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM