ruby 直接链接(无重定向)到ActiveStorage中的文件

vql8enpb  于 2023-05-17  发布在  Ruby
关注(0)|答案(4)|浏览(213)

对存储在活动存储中的文件使用url_for()将返回一个指向应用程序的url,然后重定向到实际位置。由于使用了带有CORS的bug in firefox,重定向中断了我的应用程序。
有什么方法可以通过ActiveStorage直接链接到文件吗?

nnsrf1az

nnsrf1az2#

我不得不挖掘Rails源代码来创建这个,所以我不知道它是如何推荐的,但这至少适用于磁盘存储。

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
)
vh0rcniy

vh0rcniy3#

在Rails 7中,blob.service_url不再起作用,它现在只是url
因此:record.active_storage_object.url

ogq8wdun

ogq8wdun4#

对我来说,rails_blob_url(@blog.pdf)(如果你试图将文件存储为@blog.pdf)效果最好。

相关问题