在Rails4和Mongoid4中,使用MongoDB's GridFS存储文件。
步骤1:在Gemefile文件中添加carrierwave-mongoid。
gem 'mongoid', git: 'https://github.com/mongoid/mongoid.git'
gem 'mongoid-grid_fs', github: 'ahoward/mongoid-grid_fs'
gem 'carrierwave', :git => "git://github.com/jnicklas/carrierwave.git"
gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
gem 'mini_magick', :git => 'git://github.com/probablycorey/mini_magick.git'
步骤2:创建carrierwave的配置文件config/initializers/carrierwave.rb。
#config/initializers/carrierwave.rb
CarrierWave.configure do |config|
config.storage = :grid_fs
# Storage access url
config.grid_fs_access_url = "/upload/grid"
end
步骤3:在模型中设置要存储的文件
#app/models/user.rb
class User
include Mongoid::Document
mount_uploader :avatar, AvatarUploader
end
步骤4:创建上传文件的管理器。
#app/uploaders/avatar_uploader
class AvatarUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
def store_dir
"#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :thumb do
process :resize_to_limit => [200, 200]
end
end
步骤5:创建GridFS控制器。
#app/controllers/gridfs_controller.rb
class GridfsController < ApplicationController
def serve
gridfs_path = env["PATH_INFO"].gsub("/upload/grid/", "")
begin
gridfs_file = Mongoid::GridFS[gridfs_path]
self.response_body = gridfs_file.data
self.content_type = gridfs_file.content_type
rescue
self.status = :file_not_found
self.content_type = 'text/plain'
self.response_body = ''
end
end
end
步骤6:配置路由。
#config/routes.rb
get "/upload/grid/*path" => "gridfs#serve"
现在在视图中使用 user.avatar.url 将得到一个有效文件的路径。