在创建命名文件夹之前检查它是否存在

时间:2015-10-25 14:38:41

标签: google-apps-script google-drive-api

我正在尝试将Google云端硬盘中的特定文件插入到文件夹中。我还想检查是否有名为'testFolder'的文件夹:如果是,则将文件插入到现有文件夹中,否则创建一个名为'testFolder'的文件夹。

这是我到目前为止所提出的内容,但它始终会创建一个名为'testFolder'的新文件夹(因此用户现在有10个名为'testFolder'的文件夹 - 它不会重复使用第一个文件夹)。

var copyId = /* the id of the file to copy */;
function InsertFileToFolder() {
  var file = DriveApp.getFileById(copyId);      
  var folder;
  if (folderExists() == true){                        
    folder = DriveApp.getFolder("testFolder"); //<-- No such thing in GAS i think?
  } else {
    folder = DriveApp.createFolder("testFolder");
  }
  folder.addFile(file);
}

//Check whether folder exists or not
function folderExists() {
  var folders = DriveApp.getFolders();
  var flag = false;  
  for(var i = 0; i < folders.length; i++){
    if(folders[i].getName() == 'testFolder'){
      flag = true;
      break;
    }
  }
  return flag;
}

2 个答案:

答案 0 :(得分:5)

length没有folders属性。您需要使用hasNext()

Google Documentation - Folder Class

// Log the name of every folder in the user's Drive.
var folder,folders;

folders = DriveApp.getFolders();

while (folders.hasNext()) {
  folder = folders.next();
  Logger.log(folder.getName());
}

如果找到要查找的文件夹,此代码将返回文件夹ID:

function InsertFileToFolder() {
  var file,folder,
      folderIdOrFalse;
  file = DriveApp.getFileById(copyId);      

  folderIdOrFalse = folderExists();

  if (folderIdOrFalse !== false) {                        
    folder = DriveApp.getFolderById(folderIdOrFalse);
  } else {
    folder = DriveApp.createFolder("testFolder");
  }

  folder.addFile(file);
};

function folderExists() { //Check whether folder exists or not

  var folders = DriveApp.getFolders();
  var theReturn = false,
      i=0,
      folderName = "",
      folder;  

  while (folders.hasNext()) {
    folder = folders.next();
    folderName = folder.getName();

    if (folderName === 'testFolder') {
      theReturn = folder.getId();
      break;
    };
  };

  return theReturn;
};

答案 1 :(得分:0)

谷歌改变了它的脚本。我知道这是一个老帖子,但这是我能想到的最好的答案:

function getFolder(parent_folder,folder_name){
  var folders = parent_folder.getFolders();     
  while (folders.hasNext()) {
    var folder = folders.next();
    if(folder_name == folder.getName()) {         
      return folder;
    }
  }
  return false;
}

var parent_folder = DriveApp.getFolderById(//id\\);
var folderName = getFolders(parent_folder,name);
if (folderName === false){
  folderName =  outputfolderId.createFolder(name);
}

在此答案中找到:How to create a folder if it doesn't exist?