Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active August 16, 2023 23:30
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save tanaikech/96166a32e7781fee22da9e498b2289d0 to your computer and use it in GitHub Desktop.
Save tanaikech/96166a32e7781fee22da9e498b2289d0 to your computer and use it in GitHub Desktop.
Selecting Files in Google Drive using Select Box for Google Apps Script

This is a sample script for selecting files in Google Drive using HTML select box for Google Apps Script.

Feature

Feature of this sample.

  • It is a simple and space saving.
  • When the folder is selected, the files in the folder are shown.
  • When the file is selected, the ID of file is retrieved. Users can use this ID at GAS.
  • When a folder is opened, all files in the folder are cached. By this, the second access of the folder is faster.
  • It doesn't retrieve all files in Google Drive at once, so the read of files from Google Drive becomes the minimum necessary.

I will use this for applications that users need to select files on Google Drive.

Demo

From this demonstration, it is found that when a folder is selected for the first time, the time to retrieve files is required. At the second access for the folder, the speed is faster than that for the first time. Because the data of files is cached.

Although this sample uses side bar for Spreadsheet, of course, you can also use this sample to dialog box and Web Apps.

Usage

  1. Create Spreadsheet.
  2. Open the Spreadsheet and launch script editor.
  3. Copy and paste following GAS (code.gs) to the script editor.
  4. Create new HTML file on the script editor.
  5. Copy and paste following HTML (index.html) to the created HTML file on the script editor. The file name is index.html.
  6. Run main() at GAS (code.gs).
  7. See Spreadsheet. You can see the side bar like the demonstration.

GAS : code.gs

function main() {
  SpreadsheetApp.getUi().showSidebar(
    HtmlService
    .createTemplateFromFile('index')
    .evaluate()
    .setTitle("File selector sample")
  );
}

function getFiles(e, rootFolderId) {
  var data = {};
  var idn = e;
  e = e == "root" ? DriveApp.getRootFolder().getId() : e;
  data[e] = {};
  data[e].keyname = DriveApp.getFolderById(e).getName();
  data[e].keyparent = idn == rootFolderId
    ? null : DriveApp.getFolderById(e).getParents().hasNext()
    ? DriveApp.getFolderById(e).getParents().next().getId() : null;
  data[e].files = [];
  var da = idn == "root" ? DriveApp.getRootFolder() : DriveApp.getFolderById(e);
  var folders = da.getFolders();
  var files = da.getFiles();
  while (folders.hasNext()) {
    var folder = folders.next();
    data[e].files.push({name: folder.getName(), id: folder.getId(), mimeType: "folder"});
  }
  while (files.hasNext()) {
    var file = files.next();
    data[e].files.push({name: file.getName(), id: file.getId(), mimeType: file.getMimeType()});
  }
  return data;
}

function doSomething(id) {
  // do something
  var res = id;
  return res;
}

HTML : index.html

<style>
  #select_file {
    text-align: left;
    width: 95%;
    font-size: 1em;
    margin: auto;
    height: 3em;
  }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>

<select id="select_file"></select>
<p id="id"></p>

<script>
var alldata = {};

$(function() {
  const rootFolderId = "root";
  google.script.run.withSuccessHandler(importData).getFiles(rootFolderId, rootFolderId);

  $('#select_file').change(function() {
    var id = $('#select_file').val();
    var disp = $('#select_file option:selected').text();
    if (~disp.indexOf("Folder") || ~disp.indexOf("../")) {
      $('#select_file > option').remove();
      if (alldata[id]) {
        var dat = {};
        dat[id] = alldata[id];
        importData(dat);
        return;
      } else {
        google.script.run.withSuccessHandler(importData).getFiles(id, rootFolderId);
        return;
      }
      return;
    }
    google.script.run.withSuccessHandler(output).doSomething(id);
  });
});

function importData(e) {
  var key = Object.keys(e)[0];
  if (!alldata[key]) alldata[key] = e[key];
  if (e[key]["keyparent"]) {
    $('#select_file').append($('<option>').html("./" + e[key]["keyname"]).val(key));
    $('#select_file').append($('<option>').html("../").val(e[key]["keyparent"]));
  } else {
    $('#select_file').append($('<option>').html("./" + e[key]["keyname"]).val(key));
  }
  for (var i=0; i < e[key]["files"].length; i++) {
    $('#select_file').append($('<option>')
      .html(e[key]["files"][i].mimeType == "folder" ? "[Folder]" + e[key]["files"][i].name : e[key]["files"][i].name)
      .val(e[key]["files"][i].id)
    );
  }
}

function output(res){
  $('#id').text(res);
}
</script>
  • When you want to change the top folder of the list to the specific folder, please modify root of const rootFolderId = "root"; to the folder ID of the specific folder. By this, the top folder of the list becomes the specific folder.
@achimhecht
Copy link

Hi Kanshi, works great out of the box - thX
How could I preconfigure another root folder? I.e. the parent folder of the sheet starting the script...

@fegaf123
Copy link

thank you very much, i want to ask. how to use the ID in other function to import data from that selected file to active spreadsheet?

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