Upload Files In Amazon S3 With Paperclip And Rails 4

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.
development:
  amazon_bucket_name: demo-dev
  amazon_access_key: XXXXXXXXXXXXXXXXXXXX
  amazon_access_secret: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

production:
  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
  :users:
    :avatar:
      :storage: !ruby/symbol s3
      :s3_protocol: :http
      :s3_credentials:
        <<: *default_settings
      :s3_permissions:
        :avatar: :public_read
      :default_url: '/assets/missing.png'
      :styles:
        :mini: '48x48>'
      :url: ":s3_domain_url"
      :path: 'images/:id/:style/:basename.:extension'
      :convert_options:
        :all: '-strip -auto-orient -colorspace sRGB'

development:
  <<: *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
  end
end

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,
    DemoApp::Configuration.paperclip_options[:users][:avatar]

end
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.

(1) Comments


  • W

    W3villa   2 months ago

    it works