LoginSignup
58
62

More than 5 years have passed since last update.

aws-sdkを使って簡単S3操作

Last updated at Posted at 2013-06-20

aws-sdkとは

amazonが公式で提供している、AWSをrubyから操作するためのライブラリである。

公式サイト
http://aws.amazon.com/jp/sdkforruby/

インストール

gemでインストールする。

gem install aws-sdk

使い方

インスタンスの生成

アクセスキーが必要。

instnance.rb
require 'aws-sdk'

s3 = AWS::S3.new(
  :access_key_id => 'YOUR_ACCESS_KEY_ID',
  :secret_access_key => 'YOUR_SECRET_ACCESS_KEY' 
)

bucketの操作

bucket.rb
# bucketの作成
s3.buckets.create('my-bucket')

# bucketの取得
bucket = s3.buckets['my-bucket']

s3.buckets.each do |bucket|
  puts bucket.name
end

objectの操作

object.rb
# objectの取得
object = bucket.objects['img/example.jpg']

# アップロード
object = bucket.objects['img/new.jpg']
object.write(Pathname.new('/img/file.jpg'))

# S3上のリソースをローカルに保存する
File.open('file.jpg', 'wb') do |file|
  object.read do |chunk|
     file.write(chunk)
  end
end

# 応用編
bucket.objects.with_prefix('photos/').each(:limit => 20) do |photo|
  puts photo.key
end

オブジェクトを取得する際に、prefixを指定したり、limitを指定したりできる。
上記の応用編では、'photos/'から始まるオブジェクトを20件取得している。

58
62
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
58
62