在 Google Drive API V3 中使用 update() 和 addParents 移动文件不会永久生效

Moving files with update() and addParents in Google Drive API V3 not taking permanent effect

根据 this doc 尝试使用“parent”属性上的 update() 方法将文件移动到文件夹,最初似乎可以工作,但文件“parents”更新不起作用似乎被“拯救”了。名称更改确实有效:

    $meta = new \Google_Service_Drive_DriveFile([
        'name' => 'newName',
    ]);
    $file = $this->drive->files->update($fileId, $meta, [
        'addParents' => $dirId ,
        'removeParents' => '',
        'fields' => 'id, parents',
    ]);
    
    $file->getParents();   // This lists the new parent, $dirId. All looks well, but later...

    $file2 = $this->drive->files->get($fileId);
    $file2->getParents();  // ERROR: This has now reverted to having no parents!
    $file2->getName();     // This gets the new name however, which appears to be permanent

使用 google-api-php-client v2.9.1,这是撰写本文时的最新版本。 这是使用服务帐户凭据,并移动到服务帐户创建的文件夹。没有看到错误。

我确认在您的脚本中,为了检索父文件夹 ID,使用了 $file2 = $this->drive->files->get($fileId)。当您使用 Drive API v3 时,kindnameidmimeType 的值将作为默认响应值返回。这似乎是当前的规范。我想你的问题可能是因为这个。

如果我的理解是正确的,下面的修改怎么样?

发件人:

$file2 = $this->drive->files->get($fileId);
  • 在这种情况下,返回 "parents":null。所以我认为 $file2->getParents() 可能是 ERROR: This has now reverted to having no parents!.

收件人:

$file2 = $service ->files->get($fileId, array('fields' => 'name,parents'));

$file2 = $service ->files->get($fileId, array('fields' => '*'));
  • 通过这次修改,使用了fields。这样,返回的值包括parents

参考: