ActiveStorage should give users the option to proxy files. This would allow files to be cached by a CDN (image load times for my application went from 500+ms to 50ms) . Something along the lines of this is what I’m proposing:
class BlobsController < BaseController
include ActiveStorage::SetBlob def show if ActiveStorage.redirect_to_service_url expires_in ActiveStorage.service_urls_expire_in redirect_to @blob.service_url(disposition: params[:disposition]) else stream_blob end end def stream_blob expires_in ActiveStorage.service_urls_expire_in, public: true response.headers['Content-Type'] = params[:content_type] response.headers['Content-Disposition'] = params[:disposition] @blob.download do |chunk| response.stream.write(chunk) end ensure response.stream.close end
Users looking for image loading with a CDN could set this up by setting
app.config.active_storage.redirect_to_service_url = false
app.config.active_storage.service_urls_expire_in = 1.year
I just threw this together for a project I’m working on, but I would be happy to clean this up and make a proper pull request if the Rails team is open to the idea. There’s a fair amount of people requesting this feature https://github.com/rails/rails/issues/31419 some of the solutions in this issue are directly linking to the service files, but streaming would keep the service provider abstracted away while also allowing for proper CDN caching.