首页 文章

rails 4回形针上传到亚马逊s3无法正常工作

提问于
浏览
4

我一直在关注railstutorial.org上的rails 4教程 . 我已经完成了大部分工作,该项目托管在heroku上,但现在想要将图像上传到Amazon S3 . 我已经关注了heroku网站上的指南,但是在S3(欧洲)上无法上传到我的桶 .

我正在使用paperclip 3.5.2 .

Post model

has_attached_file :post_photo,
                    styles: {
                        thumb: '100x100>',
                        square: '200x200#',
                        medium: '300x300>'
                    },
                    :storage => :s3,
                    :s3_credentials => {
                        :access_key_id => ENV['S3_KEY'],
                        :secret_access_key => ENV['S3_SECRET'] },
                    :s3_protocol => "https",
                    :path => ":class/:id/:basename_:style.:extension",
                    :url => ':s3_eu_url',
                    :bucket => 'bucket_name'

Post Controller

def post_params
  params.require(:post).permit(:post_photo, :user_username, :title, :comment, :location, :user_id)
end

config/initializers/Paperclip.rb

Paperclip.interpolates(:s3_eu_url) { |attachment, style|
  "#{attachment.s3_protocol}://s3-eu-west-1.amazonaws.com/#{attachment.bucket_name}/#{attachment.path(style).gsub(%r{^/}, "")}"
}

config/environment.rb

require 'aws/s3'
AWS::S3::DEFAULT_HOST = "s3-eu-west-1.amazonaws.com"

config/environments/production.rb

# config/environments/production.rb
  config.paperclip_defaults = {
      :storage => :s3,
      :s3_credentials => {
          :bucket => ENV['S3_BUCKET_NAME'],
          :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
          :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
      },
      :url => ':s3_eu_url',
      :path => ":class/:id/:basename_:style.:extension"
  }

1 回答

  • 4

    所以,'ve gotten this working (not with Europe S3, but that shouldn' t)在 config/environments/production.rb 中没有任何东西 - 主要是因为我使用ENV变量来帮助控制我指向哪个桶,API密钥等 .

    这是我的配置:

    config/environments/production.rb

    只有标准配置 - 与回形针无关 .

    config/initializers/paperclip.rb

    Paperclip::Attachment.default_options[:storage] = :s3
    Paperclip::Attachment.default_options[:s3_protocol] = 'http'
    Paperclip::Attachment.default_options[:s3_credentials] =
      { :bucket => ENV['AWS_BUCKET'],
        :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
        :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] }
    

    对于上述内容,您需要添加:

    Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
    Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'
    

    那么,你的 Post 模型应该只需要:

    has_attached_file :post_photo,
                        styles: {
                            thumb: '100x100>',
                            square: '200x200#',
                            medium: '300x300>'
                        }
    

    这可能很明显,但也要确保你的Gemfile中加载了 aws-sdk gem .

    如果您有疑问,请告诉我 . 我已经设置了很多次,完全有助于排除故障 . :)

相关问题