lannyboy
lannyboy

Reputation: 627

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

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?

Upvotes: 4

Views: 5120

Answers (4)

silverprize
silverprize

Reputation: 19

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

Upvotes: 1

Hafez Divandari
Hafez Divandari

Reputation: 9059

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

Upvotes: 1

Nic Strong
Nic Strong

Reputation: 6592

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

Upvotes: 5

lannyboy
lannyboy

Reputation: 627

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

Upvotes: 0

Related Questions