功能介紹
修圖軟體
Gems
ImageMagick
需要安裝,否則後面的圖片操作都會失敗
1
$ brew isntall imagemagick
檢查是否安裝成功
1
2
3
4
5
$ convert -version
Version: ImageMagick 6.8.9-7 Q16 x86_64 2014-09-11 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates: bzlib fftw freetype jng jpeg lcms ltdl lzma png tiff xml zlib
Install Gems
1
2
3
4
5
6
7
8
# Gemfile
# 二擇一
gem 'mini_magick'
# gem 'rmagick'
gem 'carrierwave'
$ bundle install
Uploader
建立uploader,命名爲image (自行決定, e.g.,file, photo … etc.)
1
$ rails g uploader image
設定Uploader
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick # 指定使用minimagick
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# 指定圖片size (同時產生其他size :thumb, :medium)
process :resize_to_fit => [800, 600]
version :thumb do
process :resize_to_fill => [200,120]
end
version :medium do
process :resize_to_fill => [400,300]
end
end
Model
建立Model,命名為photo (自行決定, e.g.,file, photo, dog, cat !!?? etc.)
1
2
$ rails g model photo image:string
$ rake db:migrate
設定 model 的uploader
1
2
3
4
# app/models/photo.rb
class Photo < ActiveRecord::Base
mount_uploader :image, ImageUploader
end
gitignore
排除測試上傳的圖片
1
2
# .gitignore
public/uploads
上傳AWS S3
Install Gems
1
2
# Gemfile
gem 'fog', group: :production
Uploader 設定Production 圖片透過fog 連接並儲存至AWS S3
1
2
3
4
5
if Rails.env.production?
storage :fog
else
storage :file
end
CarrierWave 加入fog credentials 的設定
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# config/initializers/carrier_wave.rb
CarrierWave.configure do |config|
if Rails.env.production?
config.storage = :fog
config.fog_credentials = {
provider: 'AWS',
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
region: ENV['AWS_REGION']
}
config.fog_directory = ENV['AWS_S3_BUCKET_PRODUCTION']
else
config.storage :file
end
end
AWS Variables
列出不同VPS 如何管理AWS 的變數
Heroku : Settings > Cofig Variables
AWS: figrao