Upload Files to Google Cloud Storage with Google Scripts

One of my recent project involved uploading files from Google Drive to a particular bucket in Google Cloud Storage. The front-end was created in a Google Spreadsheet where the full Google Drive path of the file is specified along with the destination bucket / folder in Google Cloud Storage.

The Google Apps Script would then automatically upload the files from Drive to Cloud Storage via a time-based trigger or can be run manually as well.

To get started, you need to go to the Google Developer’s console and enable the Google Cloud Storage API and the Google Cloud Storage JSON Data API. Also enable billing for your account to access Google Cloud Storage. Then create the API keys (OAuth 2, Web Application) with the redirect URL containing your Google Apps Script project key. The OAuth2 library for Apps Script should also be included in your project.

var params = {
  CLIENT_ID: '',
  BUCKET_NAME: 'ctrlq-bucket',
  FILE_PATH: 'folder_name/filename',
  DRIVE_FILE: 'fileID'

/* Written by Amit Agarwal */
/* Email:   Web: */

function uploadFileToGCS() {

  var service = getService();
  if (!service.hasAccess()) {
    Logger.log("Please authorize %s", service.getAuthorizationUrl());

  var blob = DriveApp.getFileById(params.DRIVE_FILE).getBlob();
  var bytes = blob.getBytes();

  var url = ''
    .replace("BUCKET", params.BUCKET_NAME)
    .replace("FILE", encodeURIComponent(params.FILE_PATH));

  var response = UrlFetchApp.fetch(url, {
    method: "POST",
    contentLength: bytes.length,
    contentType: blob.getContentType(),
    payload: bytes,
    headers: {
      Authorization: 'Bearer ' + service.getAccessToken()

  var result = JSON.parse(response.getContentText());
  Logger.log(JSON.stringify(result, null, 2));

function getService() {
  return OAuth2.createService('ctrlq')
    .setParam('access_type', 'offline')
    .setParam('approval_prompt', 'force')
    .setParam('login_hint', Session.getActiveUser().getEmail());

function authCallback(request) {
  var service = getService();
  var authorized = service.handleCallback(request);
  if (authorized) {
    return HtmlService.createHtmlOutput('Connected to Google Cloud Storage');
  } else {
    return HtmlService.createHtmlOutput('Access Denied');

/* For support and customization, see */