Rails 4: upload image to s3 using fog and carrierwave

1. Add these lines to your gemfile and run ‘bundle install’

# for aws cloud storage
gem 'fog'
# photo resizing
gem "mini_magick"
# file upload solution
gem 'carrierwave'

2. generate new carrierwave uploader using this command’rails generate uploader Avatar’
That will creates a file in ‘app/uploaders/avatar_uploader.rb’

3. Update the file with the following

# encoding: utf-8

class AvatarUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  #storage :file
  storage :fog
  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  # Provide a default URL as a default if there hasn't been a file uploaded:
  def default_url
    # For Rails 3.1+ asset pipeline compatibility:
    # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
  
    #{}"/images/fallback/" + [version_name, "default.png"].compact.join('_')
    'default_avatar.png' #rails will look at 'app/assets/images/default_avatar.png'
  end

  # Process files as they are uploaded:
  # process :scale => [200, 300]
  #
  # def scale(width, height)
  #   # do something
  # end

  # Create different versions of your uploaded files:
  version :large_avatar do
    # returns a 150x150 image
    process :resize_to_fill => [150, 150]
  end
  version :medium_avatar do
    # returns a 50x50 image
    process :resize_to_fill => [50, 50]
  end
  version :small_avatar do
    # returns a 35x35 image
    process :resize_to_fill => [35, 35]
  end

  # Add a white list of extensions which are allowed to be uploaded.
  # For images you might use something like this:
  def extension_white_list
    %w(jpg jpeg gif png)
  end
end

4. Update your user.rb with the following, assuming you already have avatar column in database with datatype string

class User < ActiveRecord::Base
  .
  .
  # Avatar uploader using carrierwave
  mount_uploader :avatar, AvatarUploader
end

5. Create a new file in ‘config/initializer/s3.rb’, and paste the following code

CarrierWave.configure do |config|
  config.fog_credentials = {
      :provider               => 'AWS',
      :aws_access_key_id      => ENV['S3_KEY'],
      :aws_secret_access_key  => ENV['S3_SECRET']
      # :region                 => ENV['S3_REGION'] # Change this for different AWS region. Default is 'us-east-1'
  }
  config.fog_directory  = ENV['S3_BUCKET']
end

6. If you are on unix machine, add the following code in your ~/.bash_profile, and run source to reload it, otherwise hardcoded the value of your access id, key and bucket in step 5.

#aws s3
export S3_KEY="SecretKeyFromAWS"
export S3_SECRET="SecRetKEy"
export S3_BUCKET="bucketname"

7. Code for upload view, pay attention to ‘:multipart => true’

 {:multipart => true} do |f| %>
    My Avatar
    

8. Code to display in view

original size


large size


medium size


small size

Leave a comment