Upload files in Amazon S3 with Paperclip and Rails 4

Amazon company logo

Here is a clean approach to set the configuration of model to upload images in Amazon S3 server with paperclip in Ruby on Rails. We need following gems in out Gemfile

gem 'paperclip'
gem 'aws-sdk'

In the config folder create a file called config/api_config.yml where you set up your bucket name, amazon access key and access secret in the file.

  amazon_bucket_name: demo-dev
  amazon_access_key: XXXXXXXXXXXXXXXXXXXX
  amazon_access_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  amazon_bucket_name: demo-prod
  amazon_access_key: XXXXXXXXXXXXXXXXXXXX
  amazon_access_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Our next step is to create a file called config/paperclip_options.yml, which will contain configurations of paperclip like styles, url, convert_options, etc

common: &default_settings
  :access_key_id: <%= API_CONFIG['amazon_access_key'] %>
  :secret_access_key: <%= API_CONFIG['amazon_access_secret'] %>
  :bucket: <%= API_CONFIG['amazon_bucket_name'] %>

production: &production
      :storage: !ruby/symbol s3
      :s3_protocol: :http
        <<: *default_settings
        :avatar: :public_read
      :default_url: '/assets/missing.png'
        :mini: '48x48>'
      :url: ":s3_domain_url"
      :path: 'images/:id/:style/:basename.:extension'
        :all: '-strip -auto-orient -colorspace sRGB'

  <<: *production

This file will set s3_credentials to the credential in api_config.yml and will set up other asset details. Now create a file named config/initializers/paperclip_config.rb which will map the configuration of above two file and set those in the environment variables of the Ruby on Rails app.

API_CONFIG = YAML.load_file("#{Rails.root}/config/api_config.yml")[Rails.env]

class DemoApp::Configuration
  class << self
    attr_accessor :paperclip_options

DemoApp::Configuration.paperclip_options = YAML.load(ERB.new(File.read(Rails.root.join('config', 'paperclip_options.yml'))).result)[Rails.env]
Paperclip::Attachment.default_options[:use_timestamp] = false

In our user model, we just need to add the mapping of the image file, we can simply do it with DemoApp::Configuration.paperclip_options[:users][:image] which we have configured in paperclip_config.rb file.

class User < ActiveRecord::Base

  has_attached_file :image,


You can create view of your choice to upload the image. Just make sure image key in the params should have a image. You can have a look at Upload image without submitting form, works on all browsers to get an idea for the controller and view code.

Recent Post



Comments (1)
  • Comment avatar
    W3villaabout 3 years agoReply

    it works

    • Comment avatar
      Susanwouroalmost 2 years agoReply

      dating my daughter friend dating a single dad with shared custody free dating sites templates farm hook up dating seth thomas metronome new york hook up app animation dating it complicated demographics online dating expat dating sao paulo expat dating china

      • Comment avatar
        Georgespono6 months agoReply

        • Comment avatar
          Georgespono6 months agoReply

          • Comment avatar
            Triujpcna5 months agoReply

            sildenafil hplc method https://viagrapdf.com/ - 100mg viagra generic lowest price viagra peruvian viagra

            • Comment avatar
              Danielinvaf4 months agoReply

              Here girls want to get acquainted! / Go to the site, register and look for a girl for sex. telegram channel: Go to the channel #best_girls_good#

              • Comment avatar
                Austinkemabout 2 months agoReply

                Онлайн-учреждение востребованных деятельностей Наши направления: Программирование Проектирование Исследование Координация Квалификации с трудоустройством Программы длительностью сильнее 1 года. Разрешают усвоить профиль с нуля, собрать портфолио, приготовить изложение и гарантированно найти работу в ходе образования. Направления Программы длительностью от нескольких недель до 1 года, каковые разрешают освоить конкретный мастерство либо инструмент и добавить его в свое резюме. Допустима рассрочка уплаты Крутые направления по программированию, маркетингу, проектированию. Успей выбрать со скидкой! 16+ Онлайн-учреждение современных digital-профессий. Документ. Портфолио. Интернатура. 16+ Больше 50000 учеников. 89% Перейти: https://bit.ly/2Eo1kec

              • Post a Comment
            • Post a Comment
          • Post a Comment
        • Post a Comment
      • Post a Comment
    • Post a Comment
  • Post a Comment
Post a Comment