0
votes

Drive api: https://developers.google.com/drive/v2/reference/files/list

I'm trying to get the id of the spreadsheet I have, but the Logger.log() returns multiple id's instead of just the one. I think it's getting the files with the same name from the recent section in google drive.

I don't know how to fix that and any help would be appreciated.

Is there a way to only search files inside of a folder using the drive api? Or how would I exclude the files in the recent section and only search files in my drive?

snippet of code:

  //get spreadsheet
  var nameId;

  var allFiles = Drive.Files.list({
    q: "title='" + name + "' and trashed=false"
  }).items;

  for (var i = 0; i < allFiles.length; i++)
  {
    if (allFiles[i].title == name)
    {
      Logger.log("true");
      nameId = allFiles[i].id;
      Logger.log("returnTemplatedTable -- name id: " + nameId);
    }
    else
    {
      Logger.log("false");
    }
  }

  var spreadsheet = SpreadsheetApp.openById(nameId).getActiveSheet();

This is the snippet of code I have that moves a file to a folder:

  //move spreadsheet to folder
  Drive.Files.update({
    "parents": [
      {
        "id": folderId
      }
    ]
  }, fileId);

But how could I search a folder instead?

 


 

var list = Drive.Files.list({
    "folderId": folderId,
    q: "title='" + name + "' and trashed=false"
  }).items;

  for (var i = 0; i < list.length; i++)
  {
    Logger.log("id: " + list[i].id);
  }
2

2 Answers

2
votes

This uses the drive api to find the name of all the files in a folder.

 function findFilesInFolder() {
    var folderId = 'folderId'
    //searches for children of a folder
    var childrenData = Drive.Children.list(folderId)
    var children = childrenData.items;

    //loops through the children and gets the name of each one
    for (var i = 0; i < children.length; i++){
      var id = children[i].id;
      var file = Drive.Files.get(id);
      Logger.log(file.title)
    }
  }
1
votes

Here's an easier way, use searchFiles(params)

Gets a collection of all files in the user's Drive that match the given search criteria. The search criteria are detailed the Google Drive SDK documentation. Note that the params argument is a query string that may contain string values, so take care to escape quotation marks correctly (for example "title contains 'Gulliver\'s Travels'" or 'title contains "Gulliver\'s Travels"').

Here's a snippet I tried:

function searchForeFile(){

    var files = DriveApp.searchFiles(
      'modifiedDate > "2013-02-28" and title contains "Gene Simmons"');
     while (files.hasNext()) {
    var file = files.next();
     Logger.log(file.getName());
  }
}

And sure enough it returned the file I was looking for:

[17-04-03 21:43:26:736 PDT] Gene Simmons KISS.pdf