Upload Files from Google Drive to Google Cloud Storage with Google Apps Script

This tutorial describes how you can upload files and folders from your Google Drive to a bucket in Google Cloud Storage using Google Apps Script.

This tutorial describes how you can upload files and folders from your Google Drive to a bucket in Google Cloud Storage using Google Apps Script. You can even set up a time-based trigger, like a cron job, that watches a folder in your Google Drive and automatically upload new incoming files to Google Cloud Storage. The same technique can also be used to upload files from Google Drive to Firebase Storage.

Create Google Cloud Storage Bucket

To get started, go to console.cloud.google.com/projectcreate and create a new Google Cloud Project. Once the project has been added, go to console.cloud.google.com/storage/create-bucket and create a new bucket. Give your bucket a unique name and select the region where you want to store your data. If the files you are uploading are private and you don’t want to make them public anytime later, you may enable the “Enforce public access prevention on this bucket” option.

Cloud Storage Service Account

Create Storage Service Account

Next, go to IAM & Admin > Service Accounts console.cloud.google.com/iam-admin/serviceaccounts/create and create a new service account. Give your service account a name and select the “Storage Admin” role. You may also want to add the “Service Account Token Creator” role to the service account, as this is required to create signed URLs for the files you upload to Google Cloud Storage.

From the list of service accounts, click the one you created in the previous step. Go to the “Keys” tab and click on “Add Key” > “Create New Key,” and select the JSON option. This will download a JSON file containing the service account credentials. You will need these credentials to upload files to Google Cloud Storage.

Write Google Apps Script Code

Go to script.new to create a new Google Apps Script project. Click on Libraries and add the OAuth2 library 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF to your project. Next, add a new file service.js, and use the values of private_key and client_email from your service account JSON file to create a new OAuth2 service.

// service.js

// Replace these with your own values
const service_account = {
  private_key: '-----BEGIN PRIVATE KEY-----\n51CjpLsH8A\n-----END PRIVATE KEY-----\n',
  client_email: 'upload@storage-labnol.iam.gserviceaccount.com',
};

const getStorageService = () =>
  OAuth2.createService('FirestoreStorage')
    .setPrivateKey(service_account.private_key)
    .setIssuer(service_account.client_email)
    .setPropertyStore(PropertiesService.getUserProperties())
    .setCache(CacheService.getUserCache())
    .setTokenUrl('https://oauth2.googleapis.com/token')
    .setScope('https://www.googleapis.com/auth/devstorage.read_write');

Upload Files to Google Cloud Storage

Next, we’ll write the upload function in Apps Script. The function takes the file ID of the file you want to upload to Google Cloud Storage, the name of the bucket, and the path where you want to store the file.

The function uses the getStorageService function from the previous step to create a new OAuth2 service. The getAccessToken method of the OAuth2 service is used to get the access token required to upload files to Google Cloud Storage.

// Replace these with your own values
const DRIVE_FILE_ID = 'abc123';
const STORAGE_BUCKET = 'labnol.appspot.com';
const FILE_PATH = 'parentFolder/subFolder';

const uploadFileToCloudStorage = () => {
  const file = DriveApp.getFileById(DRIVE_FILE_ID);
  const blob = file.getBlob();
  const bytes = blob.getBytes();

  const API = `https://www.googleapis.com/upload/storage/v1/b`;
  const location = encodeURIComponent(`${FILE_PATH}/${file.getName()}`);
  const url = `${API}/${STORAGE_BUCKET}/o?uploadType=media&name=${location}`;

  const service = getStorageService();
  const accessToken = service.getAccessToken();

  const response = UrlFetchApp.fetch(url, {
    method: 'POST',
    contentLength: bytes.length,
    contentType: blob.getContentType(),
    payload: bytes,
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });

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

Also see: File Upload Forms for Google Drive

Amit Agarwal

Amit Agarwal

Google Developer Expert, Google Cloud Champion

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.

Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

0

Awards & Titles

Digital Inspiration has won several awards since it's launch in 2004.

Google Developer Expert

Google Developer Expert

Google awarded us the Google Developer Expert award recogizing our work in Google Workspace.

ProductHunt Golden Kitty

ProductHunt Golden Kitty

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

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional (MVP) title for 5 years in a row.

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator title recognizing our technical skill and expertise.

Email Newsletter

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

We will never send any spam emails. Promise.