gem install carrierwave
gem 'carrierwave'
rails generate uploader Avatar
生成文件:app/uploaders/avatar_uploader.rb
文件上传后存储的是图片的路径,存储图片路径的字段挂载AvatarUploader.比如model Book有四个属性name 、author 、publish 、picture_url,在model中加上一行:
class Book < ActiveRecord::Base
mount_uploader :picture_url, AvatarUploader
end
# encoding: utf-8
class AvatarUploader < CarrierWave::Uploader::Base
uploader:
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
end
<p>
<%= f.label :上传图书图片 %><br />
<%= f.file_field :picture_url %>
<%= f.hidden_field :picture_url_cache %>
</p>
def create
@book = Book.new(book_params)
@book.picture_url= params[:file]
...
end
<%= image_tag @book.picture_url_url.to_s %>
carrierwave github:carrierwave