Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Cloudfront with Active Storage

I am building a website using Ruby on Rails. To upload images I am using Active Storage and Amazon S3. All's good here. Users can upload images and images are viewable on the website (images are public).

Now, in production, the url for images are: https://example.com/rails/active_storage/representations/1ej21h...

Which return a 302 to the S3 bucket: https://my-bucket.amazonaws.com/variants/9jdh2...

I am not a big fan of:

  • the two roundtrips to get the image ;
  • sending requests for images to the Rails server ;
  • the feeling of sluggishness on these images.

And I would rather like to use Cloudfront to serve these images.

I searched in Rails Guides, on Google and StackOverflow, but didn't find a proper answer so far.

Is there any solution at this time to use Cloudfront with Active Storage?

Edit: More context: Each image will be loaded 1000 times by minute at least under normal traffic and from different countries. I don't want to put the server under this pressure (it has other requests to process). And I want users to load these images as fast as possible. Hence Cloudfront as a the CDN for these images (public images, no need to get a signed url).

like image 830
Gabriel Pichot Avatar asked Sep 12 '18 10:09

Gabriel Pichot


1 Answers

Try this...

in controllers/active_storage/representations_controller.rb <--create if it doesnt exist. You should put...

module ActiveStorage
  class RepresentationsController < BaseController
    include ActiveStorage::SetBlob

    def show
      expires_in 1.year, public: true
      variant = @blob.representation(params[:variation_key]).processed
      send_data @blob.service.download(variant.key),
            type: @blob.content_type || DEFAULT_SEND_FILE_TYPE,
            disposition: 'inline'
    end
  end
end

Then when you call an image using @model.image.variant(resize: '250x250') making sure to substitute your desired dimensions. This is a hack for now. This should be fixed by rails 6 release I think.

like image 109
Verty00 Avatar answered Nov 20 '22 12:11

Verty00