4
votes

How to move a file from root to a folder with Google Drive SDK API?

I tried this, but it never work!

1) Insert the file id into a folder.
Method: https://developers.google.com/drive/v2/reference/children/insert
Result: Files are able to insert into the folder, but files are also shown in the root.

2) Remove the file id from the parent.
Method: https://developers.google.com/drive/v2/reference/parents/delete
Result: A weird result. It should remove the parent's files but this removed the children files in the folder.

Any help please?

4

4 Answers

5
votes

A simpler way is to use patch to update the parents field to the id of the new folder.

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

1
votes

Here is the one step method to move file to the new folder using Patch and the PHP 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();
  }
}
0
votes

I found a workaround

1) Copy the original files to the destination folder.
Method: https://developers.google.com/drive/v2/reference/files/copy

2) Delete the original files.
Method: https://developers.google.com/drive/v2/reference/files/delete

0
votes

I think that proper method is "Files:Patch"(https://developers.google.com/drive/v2/reference/files/patch).
You can move a file by set optional parameters that addParents, removeParents.

If I move a "0B2H_JyuGzV0AQmpOTjdTNDZXM00" from "0B2H_JyuGzV0AZHFUUzE4cXh3aXM" to root folder, do this.

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