简体   繁体   中英

How to copy a google drive document from one folder to another using JavaScript API

I have two folders Folder1 and Folder2 in my Google drive.

I have created a google drive document doc1 in Folder1. Later i need to copy this document to Folder2. How can i achieve this.

I tried the below link but its creating the copy on the same folder.

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

/**
 * Copy an existing file.
 *
 * @param {String} originFileId ID of the origin file to copy.
 * @param {String} copyTitle Title of the copy.
 */
function copyFile(originFileId, copyTitle) {
  var body = {'title': copyTitle};
  var request = gapi.client.drive.files.copy({
    'fileId': originFileId,
    'resource': body
  });
  request.execute(function(resp) {
    console.log('Copy ID: ' + resp.id);
  });
}

As I have read on this blog , there is no direct method to move files from one folder to another in Google Drive. Your option is to copy a file to another folder, set its name to the original file and then delete the original using the setTrashed(true) method of File.

Be noted that this method will fail if the file/s have been uploaded by another user while the script is running under a different user.

Here is a sample snippet:

function copyFile(originFileId, destinationFileId) {

  var files = originFileId.getFiles();

  while (files.hasNext()) {

    var file = files.next();
    file.makeCopy(target).setName(file.getName());
    file.setTrashed(true);

  }

Hope this helps! :)

Hackaround in 2020. Go to Google Colab and use ! cp path1 path2 ! cp path1 path2

You can even use -r option for directories. Pretty neat! Though I should warn you this method is slow if your folder contains a lot of files or contains large files.

Edit: typo in Colab

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM