LoginSignup
3
3

More than 3 years have passed since last update.

RubyでGoogleDriveAPIを使用してGoogleドライブにファイルをアップロードする

Last updated at Posted at 2019-06-14
  • 特定のGoogleドライブにファイルアップロードするのでoauthとかではなくサービスアカウントを作成

Google Cloud Platform

  • https://console.cloud.google.com
  • プロジェクトを作成する
  • 作成したプロジェクトでDriveAPIを有効に設定する
  • 認証情報を作成、サービスアカウントを作成してjsonをダウンロードする

DriveAPIを使用して一覧取得、アップロード

  • .envにjsonの内容を記述
  • jpegをアップロード
  • アップロードに関して注意する点はアップしたファイルに対して権限を付与しないと閲覧できないこと
  • グーグルドライブを使用するときのアカウントemailで権限付与すれば閲覧できる
.env
GOOGLE_ACCOUNT_TYPE=service_account
GOOGLE_CLIENT_ID=12345678901234567890
GOOGLE_CLIENT_EMAIL=project-example@xxxx-xxxxx-12345.iam.gserviceaccount.com
GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n 省略 \n-----END PRIVATE KEY-----\n"
files_controller
require 'googleauth'
require 'google/apis/drive_v3'

class FilesController < ApplicationController
  before_action :auth_drive

  Drive = ::Google::Apis::DriveV3

  def index

    @result = @drive_service.list_files(page_size: 20,
                               fields: 'files(name,modified_time,web_view_link),next_page_token')
  end

  def create

    uploaded_file = file_upload_param[:file]
    output_path = uploaded_file.original_filename

    File.open(output_path, 'w+b') do |fp|
      fp.write  uploaded_file.read
    end

    file_metadata = {
        name: uploaded_file.original_filename
    }
    file = @drive_service.create_file(file_metadata,
                                     fields: 'id',
                                     upload_source: output_path,
                                     content_type: 'image/jpeg')

    create_permission(file.id, 'yoshida@example.com')

    FileUtils.rm output_path

    redirect_to action: 'index'

  end

  private

  def auth_drive
    @drive_service = Drive::DriveService.new

    auth = ::Google::Auth::ServiceAccountCredentials
               .make_creds(scope: 'https://www.googleapis.com/auth/drive')
    @drive_service.authorization = auth

  end

  def create_permission(file_id, email)

    user_permission = {
        type: 'user',
        role: 'writer',
        email_address: email
    }
    @drive_service.create_permission(file_id,
                                     user_permission,
                                     fields: 'id')
  end

  def file_upload_param
    params.require(:fileupload).permit(:file)
  end
end

参考:
https://developers.google.com/drive/
https://github.com/googleapis/google-auth-library-ruby
https://www.rubydoc.info/github/google/google-api-ruby-client/Google/Apis/DriveV3

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3