Gopal Kumar
Gopal Kumar

Reputation: 147

Uploading Image from google drive to amazon S3 using app script

I am integrating google form to our backend system. In the form, we are accepting images on google drive. I am trying to move google drive images to s3 whenever a form is submitted. I am using this to fetch an image from google drive.

var driveFile = DriveApp.getFileById("imageId"); 

For uploading image to S3, I am using app script library S3-for-Google-Apps-Script. File is being uploaded to s3 but format is not correct.

code for uploading image to S3 is

var s3 = S3.getInstance(awsAccessKeyId, awsSecretKey);
s3.putObject(bucket, "file name", driveFile.getBlob(), {logRequests:true});

I am not able to open image after downloading from s3. Getting error "It may be damaged or use a file format that Preview doesn’t recognize."

Thanks in Advance.

Upvotes: 7

Views: 2334

Answers (1)

Albert Mathews
Albert Mathews

Reputation: 135

Do pip install boto3 googledrivedownloader requests first, Then use the code given below:

import boto3
from google_drive_downloader import GoogleDriveDownloader as gdd
import os


ACCESS_KEY = 'get-from-aws'
SECRET_KEY = 'get-from-aws'
SESSION_TOKEN = 'not-mandatory'
REGION_NAME = 'ap-southeast-1'
BUCKET = 'dev-media-uploader'


def drive_to_s3_download(drive_url) :
    if "drive.google" not in drive_url:
        return drive_url    #since its not a drive url.

    client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
        region_name=REGION_NAME,
        aws_session_token=SESSION_TOKEN  # Optional
    )
    file_id = drive_url.split('/')[5]
    print(file_id)
    gdd.download_file_from_google_drive(file_id=file_id,
                                        dest_path=f'./{file_id}.jpg',
                                        unzip=True)
    client.upload_file(Bucket=BUCKET, Key=f"{file_id}.jpg", Filename=f'./{file_id}.jpg')
    os.remove(f'./{file_id}.jpg')
    return f'https://{BUCKET}.s3.amazonaws.com/{file_id}.jpg'


client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
        region_name=REGION_NAME,
        aws_session_token=SESSION_TOKEN  # Optional
    )
# client.download_file(Bucket='test-bucket-drive-to-s3-upload', Key=, Filename=f'./test.jpg')
print(drive_to_s3_download('https://drive.google.com/file/d/1Wlr1PdAv8nX0qt_PWi0SJpx0IYgQDYG6/view?usp=sharing'))

The above code downloads drive file into local, then upload into S3 and then returns the S3 url, using which file can be viewed by anyone, based on permission.

Upvotes: -2

Related Questions