【问题标题】:Google Drive SDK API: How to move a file from root to a folder?Google Drive SDK API:如何将文件从根目录移动到文件夹?
【发布时间】:2013-01-03 03:33:45
【问题描述】:

如何使用 Google Drive SDK API 将文件从根目录移动到文件夹?

我试过了,但它从来没有用过!

1) 将文件 id 插入文件夹。
方法: https://developers.google.com/drive/v2/reference/children/insert
结果: 文件可以插入文件夹,但是文件也显示在根目录中。

2) 从父级中删除文件 id。
方法: https://developers.google.com/drive/v2/reference/parents/delete
结果: 奇怪的结果。它应该删除父文件,但这会删除文件夹中的子文件。

有什么帮助吗?

【问题讨论】:

    标签: google-drive-api


    【解决方案1】:

    我认为正确的方法是“Files:Patch”(https://developers.google.com/drive/v2/reference/files/patch)。
    您可以通过设置可选参数 addParents、removeParents 来移动文件。

    如果我将“0B2H_JyuGzV0AQmpOTjdTNDZXM00”从“0B2H_JyuGzV0AZHFUUzE4cXh3aXM”移动到根文件夹,请执行此操作。

    Request URL:https://content.googleapis.com/drive/v2/files/0B2H_JyuGzV0AQmpOTjdTNDZXM00?removeParents=0B2H_JyuGzV0AZHFUUzE4cXh3aXM&addParents=root&key=AIzaSyCFj15TpkchL4OUhLD1Q2zgxQnMb7v3XaM&alt=json
    Request Method:PATCH
    

    【讨论】:

      【解决方案2】:

      我找到了解决方法

      1) 将原始文件复制到目标文件夹。
      方法: https://developers.google.com/drive/v2/reference/files/copy

      2)删除原文件。
      方法:https://developers.google.com/drive/v2/reference/files/delete

      【讨论】:

        【解决方案3】:

        更简单的方法是使用patch将parents字段更新为新文件夹的id。

        https://developers.google.com/drive/v2/reference/files/patch

        【讨论】:

        • Google 建议使用 PUT 而不是 PATCH。除了动词的选择,其他都一样。
        【解决方案4】:

        这是使用PatchPHP client library 将文件移动到新文件夹的一步法:

        /**
         * 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();
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-01
          • 2018-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-06
          相关资源
          最近更新 更多