PaperClip的使用
PaperClip是Rails的一个插件,可以帮助你方便地实现文件上传的功能。官方网址是:
http://www.thoughtbot.com/projects/paperclip
安装:
gem安装方式:
在config/environment.rb中添加一行:
config.gem 'paperclip', :source => 'http://gemcutter.org'
然后运行:
rake gems:install
rake gems:unpack
插件安装方式:
script/plugin install git://github.com/thoughtbot/paperclip
PaperClip依赖于ImageMagick软件,必须先安装好这个软件。
使用方式:
写一个迁移文件:
class AddAvatarColumnsToUser < ActiveRecord::Migration
def self.up
add_column :users, :avatar_file_name, :string
add_column :users, :avatar_content_type, :string
add_column :users, :avatar_file_size, :integer
add_column :users, :avatar_updated_at, :datetime
end
def self.down
remove_column :users, :avatar_file_name
remove_column :users, :avatar_content_type
remove_column :users, :avatar_file_size
remove_column :users, :avatar_updated_at
end
end
或者用PaperClip的生成器来产生这个迁移文件:
script/generate paperclip User avatar
在模型中加入一行:
class User < ActiveRecord::Base
has_attached_file :avatar, :styles => { :medium => "300x300>", :thumb => "100x100>" }
end
编辑new和edit视图:
<% form_for :user, :html => { :multipart => true } do |form| %>
<%= form.file_field :avatar %>
<% end %>
编辑show视图:
<%= image_tag @user.avatar.url %>
<%= image_tag @user.avatar.url(:medium) %>
<%= image_tag @user.avatar.url(:thumb) %>
编辑控制器里的create方法:
def create
@user = User.create( params[:user] )
end
出现错误“Attachment C:/Users/Leon/AppData/Local/Temp/stream.3936.0 is not recognized by the 'identify' command.”的解决方法是,在development.rb中加入下面一行:
Paperclip.options[:command_path] = "/path/to/imagemagick/bin"