43
43

More than 5 years have passed since last update.

RailsでAmazon S3上に画像アップロードする

Last updated at Posted at 2012-10-26

AWSコンソールを開いて、まずは画像ファイル保存場所としてS3のbucketを用意します。
https://console.aws.amazon.com/s3/home

Gemfileに以下を足します。

Gemfile
gem 'paperclip'
gem 'aws-s3'
gem 'aws-sdk'

S3接続設定用のファイルconfig/s3.ymlを作成します。接続情報はAWSコンソールから確認できます。
東京リージョンを利用する場合はs3_host_nameを説定する必要があります。ここは軽くはまりました。

config/s3.yml
development:
  bucket: hoge-bucket
  access_key_id: xxxx
  secret_access_key: xxxx
  s3_host_name: s3-ap-northeast-1.amazonaws.com

production:
  bucket: hoge-bucket
  access_key_id: xxxx
  secret_access_key: xxxx
  s3_host_name: s3-ap-northeast-1.amazonaws.com

モデルのmigrationファイルに画像用のフィールドを追加します。

2012..._create_items.rb
class CreateItems < ActiveRecord::Migration
  def change
    create_table :items do |t|
      t.string :photo_file_name
      t.string :photo_content_type
      t.integer :photo_file_size
      t.datetime :photo_updated_at
    end
  end
end

モデル定義に画像用のフィールドを追加します。

item.rb
class Item < ActiveRecord::Base
  attr_accessible :photo

  has_attached_file :photo,
                    :styles => {
                      :thumb  => "100x100",
                      :medium => "200x200",
                      :large => "600x400"
                    },
                    :storage => :s3,
                    :s3_credentials => File.join(Rails.root, 'config', 's3.yml'),
                    :path => ":attachment/:id/:style.:extension"
end

フォームにアップロード機能を追加します。
multipart説定をして、file_fieldでアップロード用フィールドを追加します。

_form.html.erb
<%= form_for(@item, :html => {:multipart => true}) do |f| %>
  <div class="field">
    <%= f.label :photo %><br />
    <%= f.file_field :photo %>
  </div>
<% end %>

画像を表示する部分を書き加えます。

show.html.erb
<p>
  <b>Photo:</b>
  <%= image_tag @item.photo(:medium) %>
  <%= image_tag @item.photo(:thumb) %>
  <%= image_tag @item.photo(:large) %>
</p>

以上です。
heroku上でもすんなりできました。

-

参考:http://d.hatena.ne.jp/d4-1977/20120529/1338303498

43
43
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
43
43