Reputation: 2489
I would like to upload pictures from URLs by paperclip on S3 storage. I work with :
Ruby 1.9.3
Rails 3.2.6
paperclip 3.1.3
aws-sdk 1.3.9
I have my Picture Model:
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
So basically I made this to download my file from an URL:
picture = Asset.new(asset: open("http://www.my_url.com/my_picture.jpg"))
picture.save
But it save my file with a bad file_name and it doesn't set the extension of the file :
#<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.
As you can see there is no extension.
I found a method to solve it but I'm sure I can have a better way. This solution is to copy the file on my computer then I send it on S3 like this:
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
This works on my computer:
#<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"
However I don't know if this method will work on Heroku (I host my app on it).
There is not a better way without pass by a temporary file?
Upvotes: 14
Views: 4813
Reputation: 13433
Good timing. I just sent a pull request that was patched in a few hours ago (Jul 20 2012) which should make your life real easy.
self.asset = URI.parse("http://s3.amazonaws.com/blah/blah/blah.jpg")
This will download your jpeg image, ensure that the filename is blah.jpg and the content type is 'image/jpg'
Paperclip version > 3.1.3 (you'll need to link it to github repo until it gets released).
UPDATE: confirmed working with paperclip version >= 3.1.4
Upvotes: 22