2010-10-29 76 views

回答

146

這裏有一個簡單的方法:

然後簡單:

user.picture_from_url "http://www.google.com/images/logos/ps_logo2.png" 
+0

由於某種原因,我需要使用update_attribute。 – 2011-07-04 22:57:02

+0

簡單而有效。謝啦。 – goo 2012-05-25 03:03:35

+7

例如,如果您需要使用'update_attributes'將'picture_from_url'重命名爲'picture_url =(value)'。 – 2013-06-02 13:07:56

15

首先下載帶有curb寶石的圖像到TempFile,然後簡單地分配tempfile對象並保存模型。

+2

我沒有看到這個答案有什麼問題,投票結果,因爲我看到了投票。 – jpemberthy 2011-08-10 21:50:15

+0

這是最高性能的答案([by far](http://toevolve.org/2011/04/03/http-request-performance.html))。我不是一個真正的表現極客,但如果你正在用大型文件工作,這真的會加起來。 – Chip 2013-09-23 23:50:59

2

這是一個鐵桿方法:

original_url = url.gsub(/\?.*$/, '') 
filename = original_url.gsub(/^.*\//, '') 
extension = File.extname(filename) 

temp_images = Magick::Image.from_blob open(url).read 
temp_images[0].write(url = "/tmp/#{Uuid.uuid}#{extension}") 

self.file = File.open(url) 

其中Uuid.uuid只是讓一些隨機ID。

2

這可能對您有所幫助。以下是在遠程URL中使用回形針和圖像的代碼。

require 'rubygems' 
require 'open-uri' 
require 'paperclip' 
model.update_attribute(:photo,open(website_vehicle.image_url)) 

在模型

class Model < ActiveRecord::Base 
    has_attached_file :photo, :styles => { :small => "150x150>", :thumb => "75x75>" } 
end 
185

在回形針3.1.4它變得更加簡單。

def picture_from_url(url) 
    self.picture = URI.parse(url) 
end 

這比open(url)要好一些。因爲打開(url),你會得到「stringio.txt」作爲文件名。通過上面的內容,您將根據URL獲取文件的正確名稱。即

self.picture = URI.parse("http://something.com/blah/avatar.png") 

self.picture_file_name # => "avatar.png" 
self.picture_content_type # => "image/png" 
+0

如果你使用代理服務器,你如何才能實現這個功能? – Sebastian 2013-01-11 10:15:40

+3

來自paperclip wiki:https://github.com/thoughtbot/paperclip/wiki/Attachment-downloaded-from-a-URL我成功地在控制檯中運行它,該應用程序在heroku中。 – 2013-01-17 23:52:12

+3

僅供參考,對於S3 urls,我仍然將'application/octet_stream'作爲'content_type'。 – 2015-01-06 15:46:54

3

由於這些都是老答案是這裏有一個較新的一個:

添加圖像遠程URL到您所需的控制器在數據庫

$ rails generate migration AddImageRemoteUrlToYour_Controller image_remote_url:string 
$ rake db:migrate 

編輯模型

attr_accessible :description, :image, :image_remote_url 
. 
. 
. 
def image_remote_url=(url_value) 
    self.image = URI.parse(url_value) unless url_value.blank? 
    super 
end 

*在Rails4中,您必須在控制器中添加attr_accessible。

更新表單,如果你允許其他從URL

<%= f.input :image_remote_url, label: "Enter a URL" %> 
+0

什麼是「超級」? – 2014-08-26 18:46:02

+0

函數'super'用於調用原始方法,方法體的搜索從包含原始方法的對象的超類開始 – 2014-08-27 06:35:14

10

,直到我用解析URI「開放」這並沒有爲我工作的上傳圖片。 一旦我添加「打開」它的工作!

def picture_from_url(url) 
    self.picture = URI.parse(url).open 
end 

我的回形針的版本是4.2.1

打開它,就無法檢測到內容類型正確的,因爲它不是一個文件之前。它會說image_content_type:「binary/octet-stream」,即使我用正確的內容類型覆蓋它也不行。