ソースコードから理解する技術-UnderSourceCode

手を動かす(プログラムを組む)ことで技術を理解するブログ

Ruby on Rails - AWS S3からファイルを取得する

タイトル通り、AWSのS3からファイルを取得するサンプルプログラムを書いて見ました。

S3からファイルを取得する箇所をモジュールとして実装したので
そのモジュールを備忘録として載せておきます。

使用したgemは、aws-s3 です。
(aws-sdkAWSへの接続方法が違うので、注意してください。)

Gemfile

gem 'aws-s3', :require => 'aws/s3'

モジュール

require 'rubygems'
require 'aws/s3'

module Aws
include AWS::S3

BUCKET_NAME = 'your bucket name'

def self.get_files_list
connect

files = Array.new
bucket = Bucket.find(BUCKET_NAME)
bucket.objects.each do |obj|
files.push(obj.key) if obj.key.index('.')
# zipの場合は、if File.extname(obj.key) == '.zip'
end

return files
end

def self.get_file(file_path)
connect
downloaded = 'download/' + File.basename(file_path)
File.open(downloaded, 'wb') do |file|
S3Object.stream(file_path, BUCKET_NAME) do |chunk|
file.write chunk
end
end
return downloaded
end

private
def self.connect
Base.establish_connection!(
:access_key_id => 'your access_key_id',
:secret_access_key => 'your secret_access_key'
)
DEFAULT_HOST.replace('s3-ap-northeast-1.amazonaws.com')
end
end

get_files_list()では、指定したバケット内のファイルパスを配列として返しています。

get_file()では、引数で取得したファイルをS3よりダウンロードし
'download'フォルダに取得しています。

connect()は、メソッド名どおり、S3に接続するメソッドです。
注意点としては、バケットが東京リージョンにある場合
DEFAULT_HOST.replace・・・で明示的に東京リージョンを指定しないと
以下のエラーとあります。

The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.

以上です。

参考サイト
http://www.biboureq.com/mains/53
http://d.hatena.ne.jp/dkfj/20121009/1349738999
http://aws.amazon.com/articles/8621639827664165
http://qiita.com/labocho/items/45d79fc16c78bc95e1d8