代码之家  ›  专栏  ›  技术社区  ›  Qwertie

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

  •  2
  • Qwertie  · 技术社区  · 6 年前

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

    有没有办法用ActiveStorage直接链接到文件?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Jean    6 年前

    你可以这么做

    record.active_storage_object.blob.service_url

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

        2
  •  1
  •   Qwertie    6 年前

    我不得不深入研究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
  •  0
  •   Liz    6 年前

    为了我, rails_blob_url(@blog.pdf) (如果要将文件存储为 @blog.pdf )效果最好。