1. 使用七牛云存储图片

目标

注册七牛云

创建存储空间,用来存储图片

步骤

Step 1: 注册七牛云

申请个人账户

Screen Shot 2017-02-19 at 13.47.29.pngScreen Shot 2017-02-19 at 13.47.29.png

注册后需要激活邮箱

在个人面板 -> 密钥管理中,可以查看AccessKey/SecretKey,后面会用到

Screen Shot 2017-02-19 at 14.40.44.pngScreen Shot 2017-02-19 at 14.40.44.png

Step 2: 创建存储空间

Screen Shot 2017-02-19 at 19.19.53.pngScreen Shot 2017-02-19 at 19.19.53.png

这些信息后面会用到

Screen Shot 2017-02-19 at 19.26.41.pngScreen Shot 2017-02-19 at 19.26.41.png

Step 3: 在专案中设置七牛云

修改 Gemfile

...(略)
+ gem 'carrierwave-qiniu'
+ gem 'qiniu-rs'
...(略)

bundle install

bundle update

touch config/initializers/carrierwave.rb

修改 config/initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.storage             = :qiniu
  config.qiniu_access_key    = ENV["qiniu_access_key"]
  config.qiniu_secret_key    = ENV["qiniu_secret_key"]
  config.qiniu_bucket        = ENV["qiniu_bucket"]
  config.qiniu_bucket_domain = ENV["qiniu_bucket_domain"]
  config.qiniu_block_size    = 4*1024*1024   
  config.qiniu_protocol      = "http"  
  config.qiniu_up_host       = "http://up.qiniug.com"  #选择不同的区域时,up.qiniug.com 不同
end

将图片存储位置改为七牛

修改 app/uploader/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
...(略)
- storage :file
+ # storage :file
+ storage :qiniu
...(略)
git add .
git commit -m "config qiniu"

重开rails server