从新文件自动创建新的Google云端硬盘文件夹

时间:2017-06-08 14:59:29

标签: javascript google-drive-api drive

我目前正在运行Zapier流程,该流程自动创建3个从表单上传到我的Google云端硬盘中名为"新用户"的文件夹的新文件。每个文件的格式都是firstname_lastname-filename.ext,但这在组织方面并不好。

相反,我想动态创建一个标记为firstname_lastname的新文件夹,每次使用相同的firstname_lastname进入时包含3个新文件,而不是使用通用"新用户"文件夹中有数百或数千个文件。

不幸的是,我是一个非常新手的程序员,所以我不太确定如何使用Apps Script来解决这个问题。

有什么建议吗?

我想过像这样的事情:

var files = DriveApp.getFiles();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());
    if file.getName().includes("firstname_lastname") { // Check if a file name contains the string firstname_lastname
       var folders = DriveApp.getFolders();
       while (folders.hasNext()) {
          var folder = folders.next();
          Logger.log(folder.getName());
          if folder.getName().includes("firstname_lastname") { // Check if a folder exists with a name that contains the string firstname_lastname
              makeCopy(file.getName(), folder.getName()) // if said folder exists, make a copy of the the file and move it to that folder
          } else { // if said folder does not exist... 
          var newFolderName = file.getName() // let the newFolderName be the same name as the file (I know this isn't right if I want the folder name to be firstname_lastname without the actual uploaded file name plus extension)
          createFolder(newFolderName); // then create a folder that has the name newFolderName
          makeCopy(file.getName(), folder.getName(newFolderName)) // then make a copy of the file and put it into the folder
        } 
      }   
    }
  }

1 个答案:

答案 0 :(得分:0)

您可能需要先建立根文件夹“新用户”。我已经为流程创建了一个片段:

//New Users Folder
var rootFolder = DriveApp.getFolderById("FOLDER_ID");

function myFunction() {
  var files = rootFolder.getFolders();
  while (files.hasNext()) {
    var file = files.next();
    Logger.log(file.getName());

    if(file.getName() == fileuploadName){
    //copy file if folder is existing
      file.addFile(child)
    }
    else{
    //create folder
    var newFolder =  rootFolder.addFolder(child);
      newFolder.addFile(child)
    }
 }
 Logger.log("Done")

}

如果要实现动态创建文件夹,然后将文件迁移到特定文件夹名称,则此流程应该没问题。

希望这有帮助。