繁体   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