Effortless File Upload: Google Drive to Google Cloud Storage with Apps Script

Effortless File Upload: Google Drive to Google Cloud Storage with Apps Script

Learn how to use Google Apps Script to quickly move files between Google Drive and Google Cloud Storage. You will be guided through the setup procedure by this beginner’s tutorial, which starts with creating a Google Cloud Project and bucket and ends with writing the essential Apps Script code. Learn how to automate file uploads with time-based triggers to improve productivity and streamline your process. Use this detailed guide to embrace the power of integration and improve your file management skills. Get rid of manual transfers and unleash Apps Script’s potential for smooth file uploads.

Do you want to upload your Google Drive files and folders seamlessly to Google Cloud Storage? This procedure can be automated with the use of Google Apps Script, which will help you save time and work. We’ll walk you through setting up an automated file transfer in this article, and we’ll also show you how to upload files from Google Drive to Firebase Storage using the same method.

Create Your Google Cloud Storage Bucket:

Create a new Google Cloud Project to get things started. Simply create your project by going to console.cloud.google.com/projectcreate. Once finished, build a new bucket by going to console.cloud.google.com/storage/create-bucket. Don’t forget to specify the location where you want to keep your data and give your bucket a special name. Enabling the “Enforce public access prevention on this bucket” option will restrict future public access to any files that must stay private.

Create a Storage Service Account:

The following step is to create a new service account by going to IAM & Admin > Service Accounts @ console.cloud.google.com/iam-admin/serviceaccounts/create. Make sure to choose the “Storage Admin” position and give it a relevant name. The “Service Account Token Creator” role should also be added because it is required in order to create signed URLs for the files you upload to Google Cloud Storage.

Access the “Keys” page after creating the service account, click “Add Key,” then pick “Create New Key” and select the JSON option. A JSON file containing the service account credentials will be downloaded as a result. You’ll require these credentials in the future to upload files, so keep them safe.

Write Your Google Apps Script Code:

To start a fresh Google Apps Script project, go to script.new. Go to Libraries in your project and include the OAuth2 library (1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF) to ensure smooth operation. Next, make a new file called “service.js” and construct a new OAuth2 service using the values for “private_key” and “client_email” from the service account JSON file.

// 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:

It’s time to build the upload method in Apps Script now that the setup is complete. The bucket name, file path, and file ID of the file you want to upload to Google Cloud Storage are all required by this function.

// 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));
};

Now that you have a strong tool at your disposal, moving data from Google Drive to Google Cloud Storage is simple. Additionally, you can edit the Apps Script code to meet your unique needs and even plan the transfer using a time-based trigger.

Try it out to maximize Google Apps Script’s capabilities for file management and seamless Google Drive and Cloud Storage integration. Enjoy your uploads!

Congratulations! You have now mastered the use of Apps Script to easily upload files from Google Drive to Google Cloud Storage. You’ve learned a lot about automating file transfers by grasping the essential ideas and following the step-by-step instructions.

 

Leave a Comment