簡體   English   中英

如何使用 php 中的 api 重命名 google drive 中的文件或文件夾?

[英]How to rename a file or folder in google drive using the api in php?

我正在嘗試使用 php 中的 api:v2 制作一個 function 來重命名谷歌驅動器中的文件。但是據說用於重命名文件的每個 function 補丁都不存在於谷歌的驅動器文件中 '\google \apiclient-services\src\Drive\Resource\Drives.php' 文件。 我確實在其他文件中搜索過,但它不在那里。 現在如何重命名驅動器中的文件和文件夾。 我確實嘗試改變一些。

我從文檔中獲得的代碼是:-

 /**
 * Rename a file.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param string $fileId ID of the file to rename.
 * @param string $newTitle New title for the file.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if
 *     an API error occurred.
 */
function renameFile($service, $fileId, $newTitle) {
    try {
    $file = new Google_Service_Drive_DriveFile();
    $file->setTitle($newTitle);

    $updatedFile = $service->files->patch($fileId, $file, array(
        'fields' => 'title'
    ));

    return $updatedFile;
    } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
    }
}

它給出的錯誤:

    PHP Fatal error:  Uncaught Error: Call to undefined method Google\Service\Drive\DriveFile::setTitle() in .\GoogleDrive.php:153
Stack trace:
#0 .\test.php(22): GoogleDrive->renameFile('drive_Id_...', 'test2.txt')
#1 {main}
  thrown in .\GoogleDrive.php on line 153

Fatal error: Uncaught Error: Call to undefined method Google\Service\Drive\DriveFile::setTitle() in .\GoogleDrive.php:153
Stack trace:
#0 .\test.php(22): GoogleDrive->renameFile('drive_Id_...', 'test2.txt')
#1 {main}
  thrown in .\GoogleDrive.php on line 153

這很簡單。

填寫代碼為:

 /**
 * Rename a file.
 *
 * @param Google_Service_Drive $service Drive API service instance.
 * @param string $fileId ID of the file to rename.
 * @param string $newTitle New title for the file.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if
 *     an API error occurred.
 */
function renameFile($service, $fileId, $newTitle) {
    try {
    $file = new Google_Service_Drive_DriveFile();
    $file->setName($newTitle);

    $updatedFile = $service->files->update($fileId, $file);

    return $updatedFile;
    } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
    }
}

您需要更改的部分是:

  • ->patch更改為->update並將->setTitle更改為->setName

  • array('fields' => 'title')); 您需要更改刪除它。 這將給出錯誤:

     An error occurred: { "error": { "errors": [{ "domain": "global", "reason": "invalidParameter", "message": "Invalid field selection title", "locationType": "parameter", "location": "fields" }], "code": 400, "message": "Invalid field selection title" }

    }

這適用於文件和文件夾。

Google Drive V3 PHP API 文檔稀少且含糊。

要使用該版本的 API 執行相同的文件重命名操作:

$file = new Google_Service_Drive_DriveFile();
$file->setName($newTitle);
$updatedFile = $service->files->update($fileId, $file, array('fields' => 'name'));

暫無
暫無

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

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