图像上传不适用于带有s3的heroku

时间:2014-04-27 16:28:42

标签: ruby-on-rails heroku amazon-s3 paperclip

我使用Paperclip gem来处理我的Rails应用上的图片上传。一切都在开发中很好,但是当我在heroku应用程序上传图像时,我得到了#34;出了问题"错误。我检查了heroku日志,但我没有看到任何错误消息。然而,我在dev和heroku之间注意到的一个区别是开发日志显示" begin..insert into ... etc" SQL显示,而在heroku中,日志不显示任何SQL。它甚至无法写入数据库。

heroku日志只显示"参数"以及之后的一些命令:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"****", "show"=>{"name"=>"test", "description"=>"this is a description", "cover"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700fd0 @tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-1431xte>, @original_filename="bc_top.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"show[cover]\"; filename=\"bc_top.png\"\r\nContent-Type: image/png\r\n">, "thumbnail"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700eb8 @tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-al452c>, @original_filename="bc_cover.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"show[thumbnail]\"; filename=\"bc_cover.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Add show"}

然后它显示了一些其他命令,但没有错误:

Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-2i17k4.png'
2014-04-27T16:06:34.040235+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-189rb23.png'
2014-04-27T16:06:34.150632+00:00 app[web.1]: Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-bfdlsj.png'
2014-04-27T16:06:33.966054+00:00 app[web.1]:   vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-04-27T16:06:33.966069+00:00 app[web.1]: Started POST "/shows" for 76.***.***.** at 2014-04-27 16:06:33 +0000
2014-04-27T16:06:33.966071+00:00 app[web.1]: Processing by ShowsController#create as HTML
2014-04-27T16:06:34.099317+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-5r5s9s.png'
2014-04-27T16:06:34.446474+00:00 heroku[router]: at=info method=POST path=/shows host=app.herokuapp.com request_id=1bc386a4-147c-403a-9b88-55fe488ec4e3 fwd="76.***.***.**" dyno=web.1 connect=2ms service=676ms status=500 bytes=919

我完全难过了。没错!以下是相关文件:

production.rb

appName::Application.configure do
  # Settings specified here will take precedence over those in config/application.rb

  # Code is not reloaded between requests
  config.cache_classes = true

  # Full error reports are disabled and caching is turned on
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable Rails's static asset server (Apache or nginx will already do this)
  config.serve_static_assets = false

  # Compress JavaScripts and CSS
  config.assets.compress = true

  # Don't fallback to assets pipeline if a precompiled asset is missed
  config.assets.compile = true

  # Generate digests for assets URLs
  config.assets.digest = true

  config.assets.precompile = [ /\A[^\/\\]+\.(ccs|js)$/i ]

  # Defaults to nil and saved in location specified by config.assets.prefix
  # config.assets.manifest = YOUR_PATH

  # Specifies the header that your server uses for sending files
  # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx

  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
  # config.force_ssl = true

  # See everything in the log (default is :info)
  # config.log_level = :debug

  # Prepend all log lines with the following tags
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server
  # config.action_controller.asset_host = "http://assets.example.com"

  # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
  # config.assets.precompile += %w( search.js )

  # Disable delivery errors, bad email addresses will be ignored
  # config.action_mailer.raise_delivery_errors = false

  # Enable threaded mode
  # config.threadsafe!

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation can not be found)
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners
  config.active_support.deprecation = :notify

  # Log the query plan for queries taking more than this (works
  # with SQLite, MySQL, and PostgreSQL)
  # config.active_record.auto_explain_threshold_in_seconds = 0.5

  # config/environments/production.rb
  config.paperclip_defaults = {
  :storage => :s3,
  :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
  }
}

end

application.rb中

require File.expand_path('../boot', __FILE__)

require 'rails/all'

if defined?(Bundler)
  # If you precompile assets before deploying to production, use this line
  Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  # Bundler.require(:default, :assets, Rails.env)
end

module appName
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)

    # Only load the plugins named here, in the order given (default is alphabetical).
    # :all can be used as a placeholder for all plugins not explicitly named.
    # config.plugins = [ :exception_notification, :ssl_requirement, :all ]

    # Activate observers that should always be running.
    # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    # Configure the default encoding used in templates for Ruby 1.9.
    config.encoding = "utf-8"

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += [:password]

    # Enable escaping HTML in JSON.
    config.active_support.escape_html_entities_in_json = true

    # Use SQL instead of Active Record's schema dumper when creating the database.
    # This is necessary if your schema can't be completely dumped by the schema dumper,
    # like if you have constraints or database-specific column types
    # config.active_record.schema_format = :sql

    # Enforce whitelist mode for mass assignment.
    # This will create an empty whitelist of attributes available for mass-assignment for all models
    # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
    # parameters by using an attr_accessible or attr_protected declaration.
    config.active_record.whitelist_attributes = true

    # Enable the asset pipeline
    config.assets.enabled = true

    # Version of your assets, change this if you want to expire all your assets
    config.assets.version = '1.0'

    config.serve_static_assets = true

  end
end

初​​始化/ 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'] }

显示模型(带文件附件的对象)

class Show < ActiveRecord::Base
    has_many :episodes

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

    has_attached_file :cover
    validates_attachment_content_type :cover, :content_type => /\Aimage\/.*\Z/
end

我仔细检查了我的heroku配置变量,它们匹配得很好。我有一个不同的Rails 3应用程序,我想知道我是否在这个新的Rails 4应用程序上遗漏了一些东西。有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

Heroku日志并不总是有帮助。

出于您的目的,因为您刚开始使用,我建议您将heroku应用设置为&#34; development&#34;模式,以便您可以看到详细的错误消息。

heroku config # Should return a list of your current environment, including RACK_ENV=production
heroku config:add RACK_ENV=development # now you'll get verbose error messages
heroku config:add RACK_ENV=production # set this back when you're done debugging

查看日志并告诉我们您的所见。

但我建议您使用直接上传到S3。我已经写过关于将图像上传到S3(http://blog.jobspire.net/uploading-images-to-heroku/)的文章。所以看一看。

Heroku也有一个只读文件系统。这意味着Paperclip无法将上传的文件保存到Heroku中的任何位置。这可能是个问题。

  

如果您希望能够将文件上传到托管的应用程序   在Heroku上,你必须将文件存储为二进制blob   您的数据库或您必须使用单独的服务来存储文件。   如果您正在寻找单独的服务,Paperclip已内置   支持与Amazon S3集成。

请参阅相关的Heroku docs