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中进行配置
# 简单例子 models/swipephoto.rb
class Swipephoto < ActiveRecord::Base
attr_accessible :user_id , :photo
AVATAR_NW = 640
AVATAR_NH = 320 Paperclip.interpolates :user_id do |a,s|
a.instance.user_id
end has_attached_file :photo,
:styles => { :normal => ["#{AVATAR_NW}x#{AVATAR_NH}#", :jpg] },
:url => "/assets/:user_id/swipephotos/:basename.:extension",
:path => ":rails_root/public/assets/:user_id/swipephotos/:basename.:extension" validates_attachment_presence :photo
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/pjpeg', 'image/jpg', 'image/png'] end
修改view
# view/swipephotos/index
<% @swipephotos.each do |swipephoto| %>
……
<%= image_tag swipephoto.photo.url(:normal) , {"style" => "width:450px"} %>
……
<% 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
这样就可以顺利上传和保存中文命名图片啦!@_@!!