简体   繁体   中英

Serving images remotely or directly the Amazon S3 - Dragonfly Gem

I have an application on Heroku and i am using Amazon S3 for storing images. I have used all Cache technics i know but seems images load too slow and it's putting off some users.

At the moment users get

/media/W1siZiIsIjIwMTQvMDIvMjEvMjMvMjAvMDQvNTY1L01pa2VfOTIzMi5qcGciXV0/Mike_150.jpg?sha=d8993be2

According to instructions one has to use

Dragonfly.app.remote_url_for(uid)

and they will get

http://my-bucket.s3.amazonaws.com/2011/04/01/03/03/05/243/file.jpg

However when i add this line, nothing happens.

#require 'dragonfly/s3_data_store'
require 'dragonfly'

# Configure
Dragonfly.app.configure do
  plugin :imagemagick

  protect_from_dos_attacks true
  secret "2558d89a83f18f6da793e3b6dccc888c17642563e9ddedf456356f4c2d79"

  url_format '/media/:job/:name'


  response_header 'Cache-Control', 'public, max-age=3600'                    # You can set custom response headers
  response_header 'Cache-Control' do |job, request, headers|    # either directly or with a block
    job.image? ? "public, max-age=10000000" : "private"         # setting to nil removes the header
  end


  allow_legacy_urls true


  if Rails.env.test? || Rails.env.development?
    datastore :file,
              root_path: Rails.root.join('public/system/dragonfly', Rails.env),
              server_root: Rails.root.join('public')
  else
    datastore :s3,
              bucket_name: ENV['S3_BUCKET_NAME'],
              access_key_id: ENV['S3_KEY'],
              secret_access_key: ENV['S3_SECRET'],
              url_scheme: 'http',
              url_host: 'mybucket.s3.amazonaws.com'

  end

end


# Logger
Dragonfly.logger = Rails.logger

Dragonfly.app.remote_url_for(uid)

# Mount as middleware
Rails.application.middleware.use Dragonfly::Middleware

# Add model functionality
if defined?(ActiveRecord::Base)
  ActiveRecord::Base.extend Dragonfly::Model
  ActiveRecord::Base.extend Dragonfly::Model::Validations
end
  • What am i doing wrong?
  • Does services files remote url change the app performance?

You are serving images from S3 directly. Depending on where in the world your user is vs the region of the S3 bucket the latency and speed might vary.

One option to speed this up is to use AWS Cloudfront CDN and keep the S3 bucket as the origin server.

  1. Read about Cloudfront and S3
  2. Also referenced in Dargonfly

I have been struggling with this during a while. I haven't found a clean solution unfortunately but I ended with something that works.

Composing your own url string would do the job:

url = 'https://YOURBUCKET.s3.eu-central-1.amazonaws.com/' + picture.image_file_uid

I hope this can help somebody.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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