使用Paperclip和AWS S3的自定义URL

时间:2015-04-20 19:07:01

标签: ruby-on-rails ruby-on-rails-4 paperclip ruby-on-rails-4.2 aws-sdk

我们正在使用带有aws-sdk gem的Paperclip在我们的Rails应用程序中存储和显示图像:

class User < ActiveRecord::Base
  has_attached_file :image,
                    storage: :s3,
                    s3_credentials: 'config/s3.yml',
                    s3_protocol: :https,
                    styles: {
                        curriculum: '120x120>',
                        medium: '600x600>',
                        thumb: '200x200>'
                    },
                    default_url: 'missing_photo.png'
end

如果我在html.erb文件中使用<%= image_tag current_user.image.url %>,我会收到以下HTML:<img src="https://s3.amazonaws.com/<my_bucket>/users/images/000/000/001/medium/my_image.png?1419989041">

如何让https://s3.amazonaws.com/<my_bucket>成为https://example.com等自定义网址?我将我的域名全部设置在Cloudfront及其SSL证书中。

我抬头看着Paperclip S3 Storage documentation。有一个:url选项,但我没有为该选项编写任何内容。

2 个答案:

答案 0 :(得分:4)

我刚遇到这个问题,这里是我必须使用的设置

:s3_host_alias => "s3.example.com",
:url => ":s3_alias_url",
:path => ":class/:attachment/:id.:style.:extension"

this link开始,我了解到,除了:s3_host_alias:url之外,您还必须指定path,这样才能获得

Paperclip::InfiniteInterpolationError

Kinda运作良好,因为默认的回形针路径无论如何都有点不可思议。

答案 1 :(得分:2)

<强>更新

我汇总了一个例子,并且能够使用以下内容:

class User < ActiveRecord::Base

  has_attached_file :profile_picture,
                styles: { :medium => "300x300>", :thumb => "100x100>" },
                path: 'users/:attachment/:style-:hash.:extension',
                hash_secret: "94dfda08e2ed473257345563594dfda08e2ed473257345563594dfda08e2ed473257345563594dfda08e2ed4732573455635",
                default_url: "/images/:style/missing.png",
                storage: :s3,
                s3_protocol: 'http',
                url: ':s3_alias_url',
                s3_host_alias: 'distro1234.cloudfront.net',
                s3_credentials: {
                  access_key_id: 'access_id',
                  secret_access_key: 's3cr3tK3y!',
                  acl: 'private',
                  bucket: 'my-bucket',
                  bucket_url: 'https://my-bucket.s3.amazonaws.com',
                }

  validates_attachment_content_type :profile_picture, :content_type => /\Aimage\/.*\Z/

以下Gemfile

gem 'paperclip'
gem 'aws-sdk', '~> 1.5.7'

Rails控制台:

=> u.profile_picture.url
=> "http://distro1234.cloudfront.net/users/profile_pictures/original-95eb509f9c81a341945a5a65e59e81880a739d39.jpg?1429638820"

尝试这样的事情:

has_attached_file :image,
                storage: :s3,
                s3_credentials: 'config/s3.yml',
                s3_protocol: :https,
                styles: {
                    curriculum: '120x120>',
                    medium: '600x600>',
                    thumb: '200x200>'
                },
                url: ':s3_alias_url',
                s3_host_alias: 'example.com',  
                default_url: 'missing_photo.png'