跳到主要內容

使用 Paperclip 上傳圖片

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

留言

  1. 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"

    回覆刪除
  2. 上述是 bundle install paperclip 後的訊息,紀錄一下。

    回覆刪除

張貼留言

這個網誌中的熱門文章

[lyrics] Imagine

Title: Imagine Artist: John Lennon Imagine there's no Heaven It's easy if you try No hell below us Above us only sky Imagine all the people Living for today Imagine there's no countries It isn't hard to do Nothing to kill or die for And no religion too Imagine all the people Living life in peace You may say that I'm a dreamer But I'm not the only one I hope someday you'll join us And the world will be as one Imagine no possessions I wonder if you can No need for greed or hunger A brotherhood of man Imagine all the people Sharing all the world You may say that I'm a dreamer But I'm not the only one I hope someday you'll join us And the world will live as one ----------------------------- 這首歌和歌詞是早就知道的,最近又再次聽起它並認真的讀了歌詞 真的,很感動,多麼美好的世界~ (遠目) 真的也無法形容浮現在腦中的畫面.... 只能用心來感受它吧! 同樣的東西在不同的時間下會有新的,全然不同的感受.... 也有許多事情,是要親自走過、痛過、經歷過,才能了解那份感受 寫這個沒什麼意義,只是紀錄當下的感覺罷了!

白揚瀑布

 

健保卡代號

IC卡載入後,欄位代碼之表示為: *(1)代表「同意器官捐贈,不同意安寧緩和醫療」 *(4)代表「同意器官捐贈,同意安寧緩和醫療,同意不 施行心肺復甦術」 *(7)代表「不同意器官捐贈,同意安寧緩和醫療,同意 不施行心肺復甦術」 *未註記 p.s: 今天看牙醫順便請醫生幫我看一下,醫生說是代號(4),簽成功了 :) ref: http://www.tho.org.tw/xms/read_attach.php?id=259