参考にしようとしたサイトが大概aws-sdkのバージョンが古いようで動かないので、自分で書くことにする。なお、Amazon S3にファイルはアップロード済みとする。
インストール
まずはaws-sdkのバージョン2をインストール。
Gemfile
gem 'aws-sdk', '~> 2'
試す
rails console
で試してみた。
bin/rails c
ここからrails console。
アクセスキー等は適宜発行して置き換えてください。
リージョンは東京(ap-northeast-1)を指定。
バケットとファイル名を指定して、有効期限(expires_in)に60秒を設定しています。expires_inを省略した場合、デフォルトは15分の模様。
rails_console
Aws.config = { access_key_id: 'ACCESS_KEY_ID', secret_access_key: 'SECRET_ACCESS_KEY' }
s3 = Aws::S3::Client.new(region: 'ap-northeast-1')
signer = Aws::S3::Presigner.new(client: s3)
puts signer.presigned_url(:get_object, bucket: 'bucket_name', key: 'filename.png', expires_in: 60)
これで出力されたURLが、期限付きURLになります。
ブラウザでコピペして表示されたらOK。
1分後のアクセスして表示されなかったらOK。