📂

How to Upload Images to Google Drive via Ruby on Rails and View Them o

2024/02/04に公開

As I encountered difficulties while searching for how to accomplish this, I decided to write these notes for my own reference.

How to Upload Images to Google Drive via Ruby on Rails

1. Create a Service Account

  1. Go to the Google Cloud Console.
  2. Create a new project.
  3. Add a service account for the project and grant it owner access.
  4. Navigate to that service account, click on the KEYS tab, and craete new JSON keys, which will be downloaded to your PC. Save These for later use.
  5. Click on APIs & Services, select Library, then find and enable the Google Drive API to use the service.

2. Setup the Environment

  1. Install gems:
# Gemfile
gem 'google-apis-drive_v3'
gem 'googleauth'
bundle install
  1. Create a credential file:
    Save the downloaded JSON file as 'config/google_drive_service_api_key.json'.

3. Implementation

class SunabaService
  # Scope is defined in each APIs.
  # ex) https://developers.google.com/drive/api/reference/rest/v3/files/create?hl=en#authorization-scopes
  SCOPE = ['https://www.googleapis.com/auth/drive.file'].freeze
  def print_files
    files = client.list_files.files
    files.each do |file|
      puts file.name
    end
  end

  def upload_file
    metadata = Google::Apis::DriveV3::File.new(name: 'sample.jpg', parents: ['XXXXXXXXXXXXXXXXXXXXXX']) # Upload file to a specific folder
    metadata = client.create_file(metadata, upload_source: 'sample.jpg')
    pp metadata
  end

  private

    def client
      client = Google::Apis::DriveV3::DriveService.new
      client.authorization = authorizer
      client
    end

    def authorizer
      Google::Auth::ServiceAccountCredentials.make_creds(
        json_key_io: File.open('./config/google_drive_service_api_key.json'),
        scope: SCOPE
      )
    end
end

Reference

How to View Images Uploaded on Google Drive

1. Set sharing setting

Set the folder containing uploaded images to 'Anyone with the link' in the sharing settings.

2. Convert the URL

Convert the original URL of the image:
https://drive.google.com/file/d/{IMAGE ID}/view?usp=drive_link
To either:
https://drive.google.com/thumbnail?id={IMAGE ID}&sz=w1000
or
https://lh3.google.com/u/0/d/{IMAGE ID}

3. Set the URL to src Attribute of the img Tag.

<img src="https://drive.google.com/file/d/{IMAGE ID}/view?usp=drive_link" />

Reference

Discussion