Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created November 20, 2019 06:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/84dd9e9f79cad87bedb45e21342c0121 to your computer and use it in GitHub Desktop.
Save tanaikech/84dd9e9f79cad87bedb45e21342c0121 to your computer and use it in GitHub Desktop.
Moving File to Specific Folder using Google Apps Script

Moving File to Specific Folder using Google Apps Script

These are 3 sample scripts for moving a file to the specific folder in Google Drive using Google Apps Script.

Sample script 1

In this script, only Drive Service is used.

var sourceFileId = "###";
var destinationFolderId = "###";

var file = DriveApp.getFileById(sourceFileId);
DriveApp.getFolderById(destinationFolderId).addFile(file);
file
  .getParents()
  .next()
  .removeFile(file);

Sample script 2

In this script, only Drive API at Advanced Google services. (In this case, it's Drive API v2.)

var sourceFileId = "###";
var destinationFolderId = "###";

Drive.Files.update({ parents: [{ id: destinationFolderId }] }, sourceFileId);

Sample script 3

In this script, only Drive API v3 is used.

var sourceFileId = "###";
var destinationFolderId = "###";

var url1 =
  "https://www.googleapis.com/drive/v3/files/" +
  sourceFileId +
  "?fields=parents";
var res = UrlFetchApp.fetch(url1, {
  headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() }
});
var currentParent = JSON.parse(res).parents[0];
var url2 =
  "https://www.googleapis.com/drive/v3/files/" +
  sourceFileId +
  "?addParents=" +
  destinationFolderId +
  "&removeParents=" +
  currentParent;
UrlFetchApp.fetch(url2, {
  method: "patch",
  headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() }
});

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment