Google File Picker API with Google Drive - Working Example

G
Published in: Google Apps Script - Google Drive

The Google File Picker API lets users easily upload files to Google Drive and also select existing files and folders from Drive. The File Upload Forms for Google Drive is written in Google Apps Script and it lets users upload files to the form owner’s folder through the File Picker API.

Google File Picker

Here’s a complete working example that shows how to integrate the File Picker API with a Google Apps Script based web app. You’d need to enable the Google Picker API from your Google Console and also generate the developer’s key.

// Server.gs
function doGet() {
  return HtmlService.createTemplateFromFile("picker")
    .evaluate()
    .addMetaTag("viewport", "width=device-width, initial-scale=1")
    .setTitle("Google Drive Picker")
    .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

function include(fileName) {
  return HtmlService.createHtmlOutputFromFile(fileName).getContent();
}

function initPicker() {
  return {
    locale: "en",
    token: ScriptApp.getOAuthToken(),
    origin: "https://script.google.com",
    parentFolder: "xyz",
    developerKey: "ctrlq.org",
    dialogDimensions: {
      width: 600,
      height: 425,
    },
    picker: {
      viewMode: "LIST",
      mineOnly: true,
      mimeTypes: "image/png,image/jpeg,image/jpg",
      multiselectEnabled: true,
      allowFolderSelect: true,
      navhidden: true,
      hideTitle: true,
      includeFolders: true,
    },
  };
}

// For Scope
// DriveApp.getStorageUsed()
// DriveApp.getFilesByName("ctrlq.org")
// picker.html // Offers button for uploading and selecting files
<!DOCTYPE html>
<html>
  <head>
    <base target="_top" />
    <link
      rel="stylesheet"
      href="https://ssl.gstatic.com/docs/script/css/add-ons1.css"
    />
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script>
      google.load("picker", "1");
    </script>
  </head>
  <body style="margin:20px;">
    <div class="block form-group">
      <button onclick="openPicker()" type="button" class="btn btn-primary">
        Select Files
      </button>
      <button onclick="openUploader()" type="button" class="btn btn-primary">
        Upload Files
      </button>
      <div id="message"></div>
    </div>
    <?!= include("Javascript"); ?>
  </body>
</html>
// javascript.html
<script>
  function openPicker() {
    google.script.run
      .withFailureHandler(showMessage)
      .withSuccessHandler(showFilePicker)
      .initPicker();
  }

  function openUploader() {
    google.script.run
      .withFailureHandler(showMessage)
      .withSuccessHandler(showFileUploader)
      .initPicker();
  }

  function showFilePicker(config) {
    // Show all files in Google Drive for selection
    var view = new google.picker.DocsView(google.picker.ViewId.DOCS);

    view
      .setIncludeFolders(config.picker.includeFolders)
      .setSelectFolderEnabled(config.picker.allowFolderSelect)
      .setParent(config.parentFolder);

    // Show file as a grid or list (compact)
    if (config.picker.viewMode === "GRID")
      view.setMode(google.picker.DocsViewMode.GRID);
    else view.setMode(google.picker.DocsViewMode.LIST);

    if (config.picker.mimeTypes) view.setMimeTypes(config.picker.mimeTypes);

    var picker = new google.picker.PickerBuilder()
      .addView(view)
      .setLocale(config.locale)
      .setOAuthToken(config.token)
      .setDeveloperKey(config.developerKey)
      .setCallback(fileSelected)
      .setOrigin(config.origin)
      .setSize(
        config.dialogDimensions.width - 2,
        config.dialogDimensions.height - 2
      );

    if (config.picker.hideTitle) picker.hideTitleBar();

    // Show files / folders owned by the user
    if (config.picker.mineOnly)
      picker.enableFeature(google.picker.Feature.MINE_ONLY);

    if (config.picker.navhidden)
      picker.enableFeature(google.picker.Feature.NAV_HIDDEN);

    // Allow uses to select multiple files / folders
    if (config.picker.multiselectEnabled)
      picker.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);

    picker.build().setVisible(true);
  }

  function showFileUploader(config) {
    var upload = new google.picker.DocsUploadView();

    upload.setIncludeFolders(config.picker.allowFolderSelect);

    // allowFolderSelect and multiselectEnabled should be enabled
    // setting parent folder disables folder selection
    if (config.parentFolder) upload.setParent(config.parentFolder);

    // Limit the user from uploading specific types
    if (config.picker.mimeTypes) upload.setMimeTypes(config.picker.mimeTypes);

    var picker = new google.picker.PickerBuilder()
      .addView(upload)
      .setLocale(config.locale)
      .setOAuthToken(config.token)
      .setDeveloperKey(config.developerKey)
      .setCallback(fileSelected)
      .setOrigin(config.origin)
      .setSize(
        config.dialogDimensions.width - 2,
        config.dialogDimensions.height - 2
      );

    if (config.picker.hideTitle) picker.hideTitleBar();

    if (config.picker.navhidden)
      picker.enableFeature(google.picker.Feature.NAV_HIDDEN);

    if (config.picker.multiselectEnabled)
      picker.enableFeature(google.picker.Feature.MULTISELECT_ENABLED);

    picker.build().setVisible(true);
  }

  // Callback function
  function fileSelected(data) {
    var html = [];
    var action = data[google.picker.Response.ACTION];
    if (action == google.picker.Action.PICKED) {
      var documents = data[google.picker.Response.DOCUMENTS];
      for (var i = 0; i < documents.length; i++) {
        html.push(
          [
            documents[i][google.picker.Document.ID],
            documents[i][google.picker.Document.NAME],
            documents[i][google.picker.Document.MIME_TYPE],
            documents[i][google.picker.Document.URL],
          ].join("\t")
        );
      }
    } else if (action == google.picker.Action.CANCEL) {
      html.push("No file selected");
    }
    showMessage(html.join("\n"));
  }

  function showMessage(message) {
    document.getElementById("message").innerHTML = message;
  }
</script>
📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Google Apps Script - Google Drive

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
A
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account
G

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube