如何使用 php 中的 api 重命名 google 驱动器中的文件或文件夹?

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

我正在尝试使用 php 中的 api:v2 重命名 google 驱动器中的文件。但是在'\google\apiclient-services\src\Drive\Resource\Drives.php'文件中的google的drives文件中并不存在每一个据说是用来重命名文件的功能补丁。我确实在其他文件中搜索过,但它不在那里。现在如何重命名驱动器中的文件和文件夹。我确实试着改变了一些。

我从文档中得到的代码是:-

 /**
 * 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"
     }
    

    }

这对文件和文件夹都有效。