如何使用google drive API移动文件和文件夹?

Nit*_*inJ 15 google-drive-api

我正在尝试使用Google驱动程序API来执行简单的任务

  1. 跨文件夹移动文件.
  2. 项目清单

移动文件夹.

据我所知,谷歌驱动器API不提供跨文件夹移动文件的方法.

使用/ parent和/ children API可以指定文件的父文件夹,但它不适用于文件夹.此外,与文件关联的父属性不会将其移动到该文件夹​​下.它只是将父属性与文件关联起来(对我的情况来说根本没用)

int*_*cho 12

Drive API V3有:

在文件夹之间移动文件

要为现有文件添加或删除父项,请在files.update方法上使用addParents和> removeParents查询参数.

这两个参数都可用于将文件从一个文件夹移动到另一个文件夹:https: //developers.google.com/drive/v3/web/folder#inserting_a_file_in_a_folder


pin*_*yid 9

要将FILE-A从FOLDER-1移至FOLDER-2,您可以使用https://developers.google.com/drive/v2/reference/parents中的删除和添加电话来删除FOLDER-1作为父级并添加FOLDER-2.

您还可以使用更新的父阵列对文件执行修补程序.


Haf*_*ari 5

这是使用PatchPHP 客户端库将文件移动到新文件夹的一步法:

/**
 * Move a file.
 *
 * @param Google_Service_Drive_DriveFile $service Drive API service instance.
 * @param string $fileId ID of the file to move.
 * @param string $newParentId Id of the folder to move to.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if an API error occurred.
 */
function moveFile($service, $fileId, $newParentId) {
  try {
    $file = new Google_Service_Drive_DriveFile();

    $parent = new Google_Service_Drive_ParentReference();
    $parent->setId($newParentId);

    $file->setParents(array($parent));

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

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

更新:如果您想使用 Drive API v3,请使用此处记录的以下代码:

/**
 * Move a file.
 *
 * @param Google_Service_Drive_DriveFile $service Drive API service instance.
 * @param string $fileId ID of the file to move.
 * @param string $newParentId Id of the folder to move to.
 * @return Google_Service_Drive_DriveFile The updated file. NULL is returned if an API error occurred.
 */
function moveFile($service, $fileId, $newParentId) {
  try {

    $emptyFileMetadata = new Google_Service_Drive_DriveFile();
    // Retrieve the existing parents to remove
    $file = $service->files->get($fileId, array('fields' => 'parents'));
    $previousParents = join(',', $file->parents);
    // Move the file to the new folder
    $file = $service->files->update($fileId, $emptyFileMetadata, array(
      'addParents' => $newParentId,
      'removeParents' => $previousParents,
      'fields' => 'id, parents'));

    return $file;
  } catch (Exception $e) {
    print "An error occurred: " . $e->getMessage();
  }
}
Run Code Online (Sandbox Code Playgroud)