ruby -- 进阶学习(四)paperclip上传中文命名图片

     Paperclip -- 上传中文命名图片

使用Paperclip和ImageMagick插件来处理图片的时候,上传非中文命名的图片时,只要把配置写好就没问题

if you need to add image attachments to a model? See how with paperclip in this episode

创建model方法可以借鉴 :http://www.cnblogs.com/lmei/p/3231268.html

在model中进行配置

 1 # 简单例子 models/swipephoto.rb
 2 class Swipephoto < ActiveRecord::Base
 3   attr_accessible :user_id , :photo
 4   AVATAR_NW = 640
 5   AVATAR_NH = 320
 6 
 7   Paperclip.interpolates :user_id do |a,s|
 8     a.instance.user_id
 9   end
10 
11   has_attached_file :photo,
12                     :styles => { :normal => ["#{AVATAR_NW}x#{AVATAR_NH}#", :jpg] },
13                     :url  => "/assets/:user_id/swipephotos/:basename.:extension",
14                     :path => ":rails_root/public/assets/:user_id/swipephotos/:basename.:extension"
15 
16   validates_attachment_presence :photo
17   validates_attachment_size :photo, :less_than => 5.megabytes
18   validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/pjpeg', 'image/jpg', 'image/png']
19 
20 end

修改view

1  # view/swipephotos/index
2 <% @swipephotos.each do |swipephoto| %>
3       ……
4         <%= image_tag swipephoto.photo.url(:normal) , {"style" => "width:450px"} %> 
5       ……
6 <% end %>

其他修改就不详细写了~~

以上配置方法,上传非中文名的图片的时候没问题,但是当上传中文命名图片时,报错:Paperclip::NotIdentifiedByImageMagickError

这是因为ImageMagick插件无法处理中文命名图片

解决方法,就是点击上传图片后,对图片名进行重命名,下面是将图片名重命名为时间戳+随机数

# controllers/swipephoto.rb
# 对图片重命名要在new一个新的对象之前,不然会报错
# 在new一个新对象前,加上下面两句,根据具体数据类型进行修改,下面是strong Parameter类型
extension = File.extname( swipephoto_params.require(:photo).original_filename).downcase 
swipephoto_params.require(:photo).original_filename =  Time.now.strftime("%Y%m%d%H%M%S")+rand(10000).to_s+extension

附 : 关于strong parameters:http://www.cnblogs.com/lmei/p/3231330.html

这样就可以顺利上传和保存中文命名图片啦!@_@!!

posted @ 2013-08-10 00:10  lmei  阅读(590)  评论(0编辑  收藏  举报