Upload Image To S3 Using Carrierwave on Rails

This post is part of Awesome Gem series.

 

1. Add gem carrierwave

Carrierwave is gem provides a simple and extremly flexibale way to upload files from Ruby application. 

gem 'carrierwave'

gem 'fog' # Support storing file in AWS


2. Generate an uploader

rails generate uploader CoverImage 

  this should give you a file in:

app/uploader/cover_image_uploader.rb


3. Configure in uploader

It should something like this:

class CoverImageUploader < CarrierWave::Uploader::Base

  storage :fog

  
  ...

  def store_dir
    "#{Rails.env}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  ...
end


4. Mount the uploader in model (ActiveRecord)

class Post < ActiveRecord::Base
  mount_uploader :cover_image, CoverImageUploader

  ...
end


5. Configure to upload file to S3

We use the 'fog' gem which supports storing file in AWS, Google, Local and Rackspace. 

 

Create an initializer for this: 

config/initializers/carrierwave.rb

You need to configure some options like this:

CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: ENV['AWS_KEY'],
    aws_secret_access_key: ENV['AWS_SECRET_KEY'],
    region: 'ap-southeast-1'
  }
  config.fog_directory = ENV['S3_BUCKET_NAME']
end

region : should be one of [ 'eu-west-1', 'us-east-1', 'ap-southeast-1', 'us-west-1', 'ap-northeast-1' ]

fog_directory : Bucket Name in S3

 

6. Reference