paper clip

http://yuan.javaeye.com/blog/604174

好文

http://trevorturk.com/2009/03/22/randomize-filename-in-paperclip/

http://trevorturk.com/2008/12/11/easy-upload-via-url-with-paperclip/


rails console下利用paperclip处理远程URL图像的上传

悬赏:20 发布时间:2010-03-24 提问人:jackdong (初级程序员)

 

 现在已经实现了利用paperclip插件通过remote_url 更新Useravatar字段 并实现了图像上传 部分代码如下 

Ruby代码 
  1. #表单上的remote_url  
  2. attr_accessor  :image_url  
  3.   
  4. #User的avatar设置  
  5. has_attached_file :avatar:styles => {:medium=>'200x200>':thumb=> '32x32>'}  
  6.   
  7. #通过URL上传处理  
  8.   before_validation :download_remote_image:if => :image_url_provided?  
  9.   validates_presence_of :avatar_remote_url:if => :image_url_provided?, :message => '地址不合法'  
  10.   
  11. def image_url_provided?  
  12.    !self.image_url.blank?  
  13. end  
  14.   
  15. def download_remote_image  
  16.       self.avatar = do_download_remote_image  
  17.       self.avatar_remote_url = self.image_url  
  18. end  
  19.   
  20. def do_download_remote_image  
  21.       io = open(URI.parse(image_url))  
  22.       def io.original_filename; base_uri.path.split('/').last; end  
  23.       io.original_filename.blank? ? nil : io  
  24.     rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)  
  25. end  

通过这样设置后已经能够正确的处理远程URL图片的上传 但是只限于单个user对象的处理。目前Users表里有1000多条数据, 现在想做一个task, 运行后能通过批量设置用户userremote_url 然后保存  自动更新处理用户的图像上传过程(目前所有的remote_url都通过抓取另一个网站的数据得来)。个人已经试过设置userimage_url后调用down_remote_image来处理 但是没有得到预想的结果。

 

 

现在大家有什么好的建议请分享下,最好能在console下调试通过了在提, 谢谢!!

 

 

 

 

------------------------------------------------------------------------------------------------------------------
问题补充:

jsntghf 写道
把单个user对象的处理这一块代码放到model里面,def self.download_remote_image   
      self.avatar = do_download_remote_image   
      self.avatar_remote_url = self.image_url   
end 
然后,写个task 
namespace :download_image do 
  task(:record => :environment) do 
     循环user 
     User.download_remote_image 
  end 
end

才想起来我还有个问题 你这个方法不行 

已经不用上传图片了 直接改用gavatar处理了

原文地址:https://www.cnblogs.com/lexus/p/1867765.html