在Rails4中使用carrierwave-mongoid上传文件
在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'
#config/initializers/carrierwave.rbCarrierWave.configure do |config| config.storage = :grid_fs # Storage access url config.grid_fs_access_url = "/upload/grid"end
#app/models/user.rbclass User include Mongoid::Document mount_uploader :avatar, AvatarUploaderend
#app/uploaders/avatar_uploaderclass 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] endend
#app/controllers/gridfs_controller.rbclass 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 endend
#config/routes.rbget "/upload/grid/*path" => "gridfs#serve"