在网站制作过程中,图片上传以及图片的大小调整是经常会用到的一个功能!

Rails结合几个plug-in可以说很智能的做到了这一点

做了一个简单的例子,系统在Windows平台上运行

1.上网下载file-column-0.3.1.tar.gz 和rmagick-win32-1.13.0_IM-6.2.9-3.zip (我当前的最新版本,到下述站点下载 http://rubyforge.org/projects/rmagick/ Linux下版本是RMagick-1.14.1.tar.gz)

2.安装rmagick,执行zip包里面的exe文件,同时把安装路径放到path环境变量里面去,否则可能会报CORE_RL_magick_.dll找不到的错误
将压缩包中的gem文件copy到C:根目录下,然后执行
>gem install c:\rmagick-1.13.0-win32.gem

3.安装file-column到app的vendor目录里,直接copy过去就行


引用
以下的文件配置基本上按照官方提供的sample来进行,算是用中文整合一下,谈不上原创

4.建立一个存放路径的model,在数据库中建立Entry数据库
并生成相应的scaffold:
ruby script/generate scaffold Entry upload

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



改成如上即可

评论
xieqibao 2007-05-14
3.安装file-column到app的vendor目录里,直接copy过去就行

什么地方的vendor???
发表评论

您还没有登录,请登录后发表评论

koska
搜索本博客
最近加入圈子
最新评论
评论排行榜