首页 技术 正文
技术 2022年11月10日
0 收藏 392 点赞 3,710 浏览 1498 个字

     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

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295