Skip to content

Storing images on S3 and CDN's

jgu edited this page Apr 25, 2018 · 11 revisions

Solidus stores images using paperclip. You can configure paperclip to store images on s3 in your own Solidus app.

Add fog-aws to your Gemfile

# gemfile
gem 'fog-aws'

Then create a new initializer file:

# config/initializers/paperclip.rb

if Rails.application.secrets.aws_access_key_id
  Paperclip::Attachment.default_options.merge!(
    storage: :fog,
    fog_credentials: {
      provider: 'AWS',
      aws_access_key_id: Rails.application.secrets.aws_access_key_id,
      aws_secret_access_key: Rails.application.secrets.aws_secret_access_key,
      region: Rails.application.secrets.s3_region_name,
    },
    fog_directory: Rails.application.secrets.s3_bucket_name
  )

  Spree::Image.attachment_definitions[:attachment].delete(:url)
  Spree::Image.attachment_definitions[:attachment].delete(:path)
end

If using Cloudfront or other CDN, the following method may work. The gem "aws-sdk", "< 2.0" will help. Note that you need to use version 2.0 or below.

# config/initializers/aws.rb

attachment_config = {
  s3_credentials: {
    access_key_id:     Rails.application.secrets.aws_access_key_id,
    secret_access_key: Rails.application.secrets.aws_secret_access_key,
    bucket:            Rails.application.secrets.s3_bucket_name
  },

  storage:        :s3,
  s3_headers:     { 'Cache-Control' => 'max-age=31557600' },
  s3_protocol:    'https',
  s3_region:      Rails.application.secrets.s3_region,
  url:            ':s3_alias_url',
  s3_host_alias:  Rails.application.secrets.cdn_host,
  bucket:         Rails.application.secrets.s3_bucket_name,

  styles: {
    mini:     '48x48>',
    small:    '100x100>',
    product:  '240x240>',
    large:    '600x600>'
  },

  path:          '/products/:id/:style/:basename.:extension',
  default_url:   'noimage/:style.png',
  default_style: 'product',
}

attachment_config.each do |key, value|
   Spree::Image.attachment_definitions[:attachment][key.to_sym] = value
end unless Rails.env.test?