Paperclip 是一個以 rmagick 為基礎,可以幫忙處理圖片上傳的 gem。
以上傳到 S3 為例子,首先在 Gemfile 裡加入
gem 'paperclip'
gem 'aws-s3'
接著在 config/aws.yml 加入自己的 secret key 和 id
access_key_id: (your-key-id)
secret_access_key: (your-key)
假設現在希望為 User model 建立使用者的大頭照,則
rails g paperclip user avatar
上述動作會在 table users 建立 paperclip 所需要的相關欄位,因此會新增一個 migration file,記得要更新資料庫(rake db:migrate)
最後,我們要在 User model 設定 paperclip 需要的 attachment
class User < ActiveRecord::Base
以上傳到 S3 為例子,首先在 Gemfile 裡加入
gem 'paperclip'
gem 'aws-s3'
接著在 config/aws.yml 加入自己的 secret key 和 id
access_key_id: (your-key-id)
secret_access_key: (your-key)
假設現在希望為 User model 建立使用者的大頭照,則
rails g paperclip user avatar
上述動作會在 table users 建立 paperclip 所需要的相關欄位,因此會新增一個 migration file,記得要更新資料庫(rake db:migrate)
最後,我們要在 User model 設定 paperclip 需要的 attachment
class User < ActiveRecord::Base
has_attached_file :avatar,
:styles => {
:medium => "300x300#",
:thumb => "100x100" },
# Upload to S3
:storage => :s3,
:s3_credentials => "#{RAILS_ROOT}/config/aws.yml",
:path => ":attachment/:id/:style/:basename.:extension",
:bucket => 'your-bucket-name',
end
Style 可以自行設定圖片大小,paperclip 會幫我們以中心點為基礎,依大小裁切好。
取用時以 user.avatar.url(:thumb) 即可取得圖片在 S3 的 url。
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
回覆刪除Post-install message from paperclip:
##################################################
# NOTE FOR UPGRADING FROM PRE-3.0 VERSION #
##################################################
Paperclip 3.0 introduces a non-backward compatible change in your attachment
path. This will help to prevent attachment name clashes when you have
multiple attachments with the same name. If you didn't alter your
attachment's path and are using Paperclip's default, you'll have to add
`:path` and `:url` to your `has_attached_file` definition. For example:
has_attached_file :avatar,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
上述是 bundle install paperclip 後的訊息,紀錄一下。
回覆刪除