Insert the file into the drive folder (check if the folder exists, otherwise create a folder)

I am trying to insert a specific file into Google Drive in a folder. I also want to check if there is a folder named "testFolder" if "Yes", then paste the file into this already existing folder, otherwise create it with the name "testFolder".

Here is what I have come up with so far. But it always creates a new folder called "testFolder", so now users have 10 folders called "testFolder". (He cannot reuse the first folder).

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

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

  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;
}
+4
source share
2 answers

length folders. hasNext().

Google -

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

folders = DriveApp.getFolders();

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

, :

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;
};
+5

Google . , , , :

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

: , ?

0

Source: https://habr.com/ru/post/1613105/


All Articles