繁体   English   中英

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

[英]rails 4 paperclip upload to amazon s3 not working

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

我正在使用paperclip 3.5.2。

发布模型

  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' 

后控制器

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

配置/初始化/ 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"

配置/环境/ 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"
  }

所以,我已经得到了这个工作(不是欧洲S3,但这不重要)在config/environments/production.rb没有任何东西 - 主要是因为我使用ENV变量来帮助控制我指向哪个桶at,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。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM