2012-07-17 51 views
13

我想通過S3存儲上的回形針上傳URL中的圖片。 我一起工作:回形針:從帶有擴展名的網址上傳

Ruby 1.9.3 
Rails 3.2.6 
paperclip 3.1.3 
aws-sdk 1.3.9 

我有我的圖片型號:

class Asset 

    has_attached_file :asset, 
    :styles => {:thumb => "60x60>"}, 
    :storage => :s3, 
    :s3_credentials => "#{Rails.root}/config/s3.yml", 
    :path => "/pictures/:id/:style.:extension" 

    validates_attachment_content_type :asset, :content_type => ['image/gif', 'image/jpeg', 'image/png', 'image/x-ms-bmp'] 

end 

所以基本上我做這從一個URL下載我的文件:

picture = Asset.new(asset: open("http://www.my_url.com/my_picture.jpg")) 
picture.save 

但救我的文件與一個錯誤的文件名,它不會設置該文件的擴展名:

#<Asset id: 5, asset_file_name: "open-uri20120717-6028-1k3f7xz", asset_content_type: "image/jpeg", asset_update_at: nil, asset_file_size: 91565, created_at: "2012-07-17 12:41:40", updated_at: "2012-07-17 12:41:40"> 
p.asset.url 
    => http://s3.amazonaws.com/my_assets_path/pictures/5/original. 

正如你所看到的,沒有擴展。

我找到了解決方法,但我相信我可以有更好的方法。該解決方案是將文件複製我的電腦上,然後我把它放在S3這樣的:

filename = "#{Rails.root}/tmp/my_picture.jpg" 
open(filename, 'wb') do |file| 
    file << open("http://www.my_url.com/my_picture.jpg").read 
end 

picture = Asset::Picture.new(asset: open(filename)) 
picture.save 

此作品在我的電腦上:

#<Asset::Picture id: 10, asset_file_name: "my_picture.jpg", asset_content_type: "image/jpeg", asset_update_at: nil, asset_file_size: 91565, created_at: "2012-07-17 12:45:30", updated_at: "2012-07-17 12:45:30"> 
p.asset.url 
    => "http://s3.amazonaws.com/assets.tests/my_assets_path/10/original.jpg" 

不過,我不知道這種方法將工作在Heroku上(我託管我的應用程序)。

沒有臨時文件傳遞沒有更好的方法?

回答

22

良好的時機。我剛剛發送了一個在幾個小時前(2012年7月20日)修復過的請求,這會讓你的生活變得很容易。

self.asset = URI.parse("http://s3.amazonaws.com/blah/blah/blah.jpg") 

這將下載您的JPEG圖像,確保文件名是blah.jpg和內容類型是「圖像/ JPG」

回形針版> 3.1.3(你需要將它連結github回購,直到它被釋放)。

更新:已確認使用回形針版本> = 3.1.4

+2

您提交的作品就像一個魅力!它現在包含在回形針3.1.4 這是我想要的。真的很好!謝謝! – 2012-07-26 07:41:44

+2

確認,與回形針3.1.4很好。你讓我今天很開心。謝謝! – 2012-08-16 08:59:21