在网站制作过程中,图片上传以及图片的大小调整是经常会用到的一个功能!
Rails结合几个plug-in可以说很智能的做到了这一点
做了一个简单的例子,系统在Windows平台上运行
1.上网下载file-column-0.3.1.tar.gz 和rmagick-win32-1.13.0_IM-6.2.9-3.zip (我当前的最新版本,找不到上google搜索)
2.安装rmagick,执行zip包里面的exe文件,同时把安装路径放到path环境变量里面去,否则可能会报CORE_RL_magick_.dll找不到的错误
3.安装file-column到app的vendor目录里,直接copy过去就行
4.建立一个存放路径的model,在数据库中建立Entry数据库并生成相应的scaffold:
ruby script/generate scaffold Entry
4.修改model,并限制只能图片上传
class Entry < ActiveRecord::Base
validates_format_of :image,
:with=>/^.*(.jpg|.JPG|.gif|.GIF)$/,
:message => "你只能上传JPG或则GIF的图片文件" 
file_column :image, :magick => ...{ 
:versions => ...{ "thumb" => "50x50", "medium" => "640x480>" }
}
end 5.修改_form.rhtml
<%= error_messages_for 'entry' %>
<!--[form:entry]-->
<p><label for="entry_image">Image</label><br/>
<%= file_column_field 'entry', 'image' %></p>
<!--[eoform:entry]--> 6.修改new.rhtml
<h1>New entry</h1>
<%= start_form_tag 'create',:multipart => true%>
<%= render :partial => 'form' %>
<%= submit_tag "Create" %>
<%= end_form_tag %>
<%= link_to 'Back', :action => 'list' %> 7.修改show.rhtml
<% for column in Entry.content_columns %>
<p>
<b><%= column.human_name %>:</b> <%=h @entry.send(column.name) %>
<br>
原始大小:
<%= image_tag url_for_file_column 'entry', 'image' %>
<br>
thumb:
<%= image_tag url_for_file_column 'entry', 'image' ,'thumb'%>
<br>
medium:
<%= image_tag url_for_file_column 'entry', 'image' ,'medium'%>
</p>
<% end %>
<%= link_to 'Edit', :action => 'edit', :id => @entry %> |
<%= link_to 'Back', :action => 'list' %> 
大功告成!
上传一张图片,会自动生成预缆图片
但是有个问题,发现扩展名是大写时会出错
解决办法:
vendor/plugins/file-column-0.3.1/lib下file_column.rb文件
里的
#FileUtils.mv(local_file_path, new_local_file_path) unless new_local_file_path == local_file_path
#modified by victor;
FileUtils.mv(local_file_path, new_local_file_path) unless new_local_file_path.downcase == local_file_path.downcase
改成如上即可
1万+




被折叠的 条评论
为什么被折叠?



