对存储在活动存储中的文件使用url_for()将返回一个指向应用程序的url,然后重定向到实际位置。由于使用了带有CORS的bug in firefox,重定向中断了我的应用程序。有什么方法可以通过ActiveStorage直接链接到文件吗?
url_for()
xj3cbfub1#
你能做到的record.active_storage_object.blob.service_url在此找到https://github.com/rails/rails/blob/master/activestorage/app/controllers/active_storage/blobs_controller.rb
record.active_storage_object.blob.service_url
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 )
vh0rcniy3#
在Rails 7中,blob.service_url不再起作用,它现在只是url。因此:record.active_storage_object.url
blob.service_url
url
record.active_storage_object.url
ogq8wdun4#
对我来说,rails_blob_url(@blog.pdf)(如果你试图将文件存储为@blog.pdf)效果最好。
rails_blob_url(@blog.pdf)
@blog.pdf
4条答案
按热度按时间xj3cbfub1#
你能做到的
record.active_storage_object.blob.service_url
在此找到https://github.com/rails/rails/blob/master/activestorage/app/controllers/active_storage/blobs_controller.rb
nnsrf1az2#
我不得不挖掘Rails源代码来创建这个,所以我不知道它是如何推荐的,但这至少适用于磁盘存储。
vh0rcniy3#
在Rails 7中,
blob.service_url
不再起作用,它现在只是url
。因此:
record.active_storage_object.url
ogq8wdun4#
对我来说,
rails_blob_url(@blog.pdf)
(如果你试图将文件存储为@blog.pdf
)效果最好。