Direct link (no redirect) to files in ActiveStorage
Asked Answered
A

4

8

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?

Aruwimi answered 7/8, 2018 at 7:13 Comment(3)
I know you've fixed this using the solution that @jean posted, but have you tried setting up a CORS policy so that you can continue using url_for (or polymorphic_url). At least that way you will be able to keep the path to your assets hidden from public, which can have all sorts of benefits.Bombardier
@Bombardier CORS is set up properly but the old version of the CORS spec said don't follow redirects and firefox hasn't changed it yet.Aruwimi
that's strange because I'm seeing no CORS related problems with firefox at all. Perhaps they've quietly fixed it. Running the latest, on Ubuntu 18. Oh well.Bombardier
T
7

You can do this

record.active_storage_object.blob.service.url

Found here https://github.com/rails/rails/blob/main/activestorage/app/models/active_storage/blob.rb#L213

Taka answered 18/9, 2018 at 10:3 Comment(3)
yeah, that seems to be a more direct way of the method I found.Aruwimi
Your link returns a 404: github.com/rails/rails/blob/master/activestorage/app/…Rior
Thanks, method and link has been fixed!Taka
A
3

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
)
Aruwimi answered 9/8, 2018 at 13:38 Comment(0)
O
2

In Rails 7 blob.service_url doesn't work anymore, it's simply url now.

So: record.active_storage_object.url

Opportunism answered 10/5, 2023 at 16:57 Comment(0)
M
0

For me, rails_blob_url(@blog.pdf) (if you're trying to get the file stored as @blog.pdf) worked best.

Mulvey answered 18/9, 2018 at 15:8 Comment(1)
This gives you the redirect urlOpportunism

© 2022 - 2024 — McMap. All rights reserved.