【问题标题】:Direct link (no redirect) to files in ActiveStorage直接链接(无重定向)到 ActiveStorage 中的文件
【发布时间】:2018-08-07 07:13:32
【问题描述】:

对存储在活动存储中的文件使用url_for() 会返回一个指向应用程序的 url,然后重定向到实际位置。由于带有 CORS 的 bug in firefox,重定向会破坏我的应用程序。

有什么方法可以通过 ActiveStorage 获得文件的直接链接?

【问题讨论】:

  • 我知道您已经使用 @jean 发布的解决方案解决了这个问题,但是您是否尝试过设置 CORS 策略以便您可以继续使用 url_for(或 polymorphic_url)。至少通过这种方式,您将能够保持资产的路径不被公开,这可以带来各种好处。
  • @stephenmurdoch CORS 已正确设置,但旧版本的 CORS 规范说不遵循重定向,Firefox 尚未更改它。
  • 这很奇怪,因为我没有看到与 Firefox 相关的 CORS 问题。也许他们已经悄悄地修复了它。在 Ubuntu 18 上运行最新版本。哦,好吧。

标签: ruby-on-rails ruby rails-activestorage


【解决方案1】:

你可以这样做

record.active_storage_object.blob.service_url

在这里找到https://github.com/rails/rails/blob/master/activestorage/app/controllers/active_storage/blobs_controller.rb

【讨论】:

  • 是的,这似乎是我找到的方法的一种更直接的方式。
【解决方案2】:

我必须深入研究 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
)

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-07
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 2011-03-27
      相关资源
      最近更新 更多