Google File Picker API with Google Drive - Working Example

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="form-group block">
      <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>

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻