Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct link (no redirect) to files in ActiveStorage

Using url_for() on a file stored in active storage returns a url that leads to the application and then redirects to the actual location. Because of a bug in firefox with CORS, the redirect breaks my application.

Is there any way to get the direct link to the file with ActiveStorage?

like image 734
Qwertie Avatar asked Aug 07 '18 07:08

Qwertie


2 Answers

You can do this

record.active_storage_object.blob.service_url

Found here https://github.com/rails/rails/blob/master/activestorage/app/controllers/active_storage/blobs_controller.rb

like image 63
Jean Avatar answered Sep 28 '22 10:09

Jean


I had to dig through the rails source to create this so I have no idea how recommended it is but this works for disk storage at least.

ActiveStorage::Current.host = "yourhostname"
attachment_blob = ActiveStorage::Attachment.find_by(record_type: "YourModel", record_id: record.id).blob
direct_url = ActiveStorage::Blob.service.url(
    attachment_blob.key,
    expires_in: 20000,
    disposition: "attachment",
    filename: attachment_blob.filename,
    content_type: attachment_blob.content_type
)
like image 30
Qwertie Avatar answered Sep 28 '22 10:09

Qwertie