rails mongoid + carrierwave

中间插件:gem 'carrierwave-mongoid' 

使用MongoDB's GridFS存储文件。

 

1、在Gemefile文件中添加carrierwave-mongoid

        gem 'mongoid'

        gem 'mongoid-grid_fs'

        gem 'carrierwave'

        gem 'carrierwave-mongoid'

        gem 'mini_magick'

 

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"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值