首页 > 解决方案 > 将 Cloudfront 与 Active Storage 结合使用

问题描述

我正在使用 Ruby on Rails 构建一个网站。要上传图片,我使用 Active Storage 和 Amazon S3。这里一切都很好。用户可以上传图片,图片可以在网站上查看(图片是公开的)。

现在,在生产中,图片的网址是:https ://example.com/rails/active_storage/representations/1ej21h ...

它将 302 返回到 S3 存储桶: https ://my-bucket.amazonaws.com/variants/9jdh2 ...

我不是以下产品的忠实粉丝:

而且我更愿意使用 Cloudfront 来提供这些图像。

我在 Rails Guides、Google 和 StackOverflow 上进行了搜索,但到目前为止还没有找到正确的答案。

目前是否有任何解决方案可以将 Cloudfront 与 Active Storage 结合使用?

编辑:更多上下文:每个图像将至少在正常流量和来自不同国家的情况下每分钟加载 1000 次。我不想让服务器承受这种压力(它还有其他请求要处理)。我希望用户尽快加载这些图像。因此 Cloudfront 作为这些图像的 CDN(公共图像,无需获取签名的 url)。

标签: ruby-on-railsamazon-s3ruby-on-rails-5amazon-cloudfrontrails-activestorage

解决方案


尝试这个...

controllers/active_storage/representations_controller.rb<--如果它不存在则创建。你应该放...

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

@model.image.variant(resize: '250x250')然后,当您使用确保替换所需尺寸来调用图像时。这是一个黑客。我认为这应该由 rails 6 release 修复。


推荐阅读