2010-11-10 49 views
0

我想知道如果我有照片的網址,我可以使用回形針將它保存在我的網站上嗎?如果是這樣如何?我可以使用回形針上傳圖片(保存副本)嗎?

+0

有人回答了您的問題嗎? – 2010-11-11 15:04:22

+0

感謝您的回答。它只是花了我一些時間來嘗試一下 – Tam 2010-11-11 21:56:37

回答

3

是的,這其實很簡單。有我的用戶模型使用頭像的代碼:

#a part of your model 
    has_attached_file :avatar, :styles => { :thumb => "50x50" }, :storage => :s3, 
         :path => "/:attachment/:id/:style/:filename", 
         :s3_credentials => Rails.root.join("config/s3.yml") 

    attr_accessor :avatar_url 

    before_validation :download_remote_file, :if => :avatar_url_provided? 

    def avatar_url_provided? 
    !self.avatar_url.blank? 
    end 

    def download_remote_file 
    self.avatar = do_download_remote_file 
    end 

    def do_download_remote_file 
    io = open(URI.parse(avatar_url)) 
      def 
       io.original_filename 
       base_uri.path.split('/').last 
      end 
    io.original_filename.blank? ? nil : io 
     rescue Exception => exc 
     logger.debug "ERROR WHEN DOWNLOADING REMOTE AVATAR FOR USER #{self.id} AND REMOTE URL #{self.avatar_url} - ERROR IS #{exc.message}" 
    end 
1

當然你可以做到

+0

無瑕的程序員邏輯=) – 2010-11-10 08:24:04

相關問題