我有一份产品清单。对于每个产品,我有一个image_url
我想要上传到我的AWS S3帐户并与之关联。
我可以通过表格手动完成,但是有大约1500种产品,我不能一个接一个地做。
我的Paperclip配置如下所示:
config.paperclip_defaults = {
:url => 'xxxx',
:path => '/:class/:attachment/:id_partition/:style/:filename',
:command_path => "/usr/bin/convert",
:storage => :s3,
:s3_credentials => {
:bucket => "xxx",
:access_key_id => "XXX",
:secret_access_key => "XXXX"
}
}
以下是我用来手动上传图片的代码
class Product < ActiveRecord::Base
# This method associates the attribute ":image" with a file attachment
has_attached_file :image, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
一切顺利,我可以在日志的末尾看到:
[paperclip] saving /products/images/000/001/361/original/xxx.jpg
[AWS S3 200 1.107584 0 retries] put_object(:acl=>:public_read,:bucket_name=>"xxx",:content_length=>47766,:content_type=>"image/jpeg",:data=>Paperclip::UploadedFileAdapter: xxx.jpg,:key=>"products/images/000/001/361/original/xxx.jpg")
[paperclip] saving /products/images/000/001/361/thumb/xxx.jpg
[AWS S3 200 0.444224 0 retries] put_object(:acl=>:public_read,:bucket_name=>"xxx",:content_length=>26502,:content_type=>"image/jpeg",:data=>Paperclip::FileAdapter: 3ef480ec0ebbef3921b4c074897fecc320150625-13674-roduas,:key=>"products/images/000/001/361/thumb/xxx.jpg")
[paperclip] saving /products/images/000/001/361/square/xxx.jpg
[AWS S3 200 0.492781 0 retries] put_object(:acl=>:public_read,:bucket_name=>"xxx",:content_length=>36071,:content_type=>"image/jpeg",:data=>Paperclip::FileAdapter: 3ef480ec0ebbef3921b4c074897fecc320150625-13674-1xrcndz,:key=>"products/images/000/001/361/square/xxx.jpg")
[paperclip] saving /products/images/000/001/361/medium/xxx.jpg
[AWS S3 200 0.553079 0 retries] put_object(:acl=>:public_read,:bucket_name=>"xxx",:content_length=>43927,:content_type=>"image/jpeg",:data=>Paperclip::FileAdapter: 3ef480ec0ebbef3921b4c074897fecc320150625-13674-8dq1h4,:key=>"products/images/000/001/361/medium/xxx.jpg")
但现在我想自动执行此任务(在播种数据库时)。我添加了open-uri
以从其网址中检索图片。
require 'open-uri'
class Product < ActiveRecord::Base
# This method associates the attribute ":image" with a file attachment
has_attached_file :image, styles: {
thumb: '100x100>',
square: '200x200#',
medium: '300x300>'
}
# Validate the attached image is image/jpg, image/png, etc
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
def image_from_url(url)
self.image = URI.escape(url)
end
end
我基本上做的是用以下内容创建一个新产品:
Product.create! :name => "Test!!!"
然后尝试添加图片:
Product.last.image_from_url "MY_URL"
我没有错误,但它不起作用。我可以在日志中看到每种格式(拇指,方形,中等)的转换,但不像以前那样推送到AWS。
答案 0 :(得分:1)
我写完后就找到了问题的解决方案。 也许它可以帮助某人,所以无论如何我都发布了它。
错误是我没有更新属性图像。所以不要这样做:
Product.last.image_from_url "MY_URL"
我做了:
Product.last.update_attribute :image, Product.last.image_from_url("MY_URL")
现在生成的图像 AND 已上传到AWS