将 ActiveStorage blob 作为 blob 获取
Get ActiveStorage blob as a blob
我正在构建一个 Rails 应用程序,它允许用户直接在浏览器中访问某些上传的文件,但 URL 与实际文件不同。这样可以通过强制登录来保护文件。
例如,您可以访问位于以下位置的文件:domain.com/file/19371da
过去,我是通过使用 CarrierWave 完成此操作的,然后对文件本身执行 to_blob
,然后使用 send_data
并使用数据库中存储的有关文件的数据将其发回:
send_data @file.file.to_blob, stream: false, filename: @file.name, type: @file.mime_type, disposition: 'inline'
然而,当使用新的 Active Storage 作为 CarrierWave 的潜在替代品时,我在将实际文件本身作为 blob 传递给 send_data
方法时遇到了障碍。
例如
send_data @file.file.to_blob, stream: false, filename: @file.file.blob.filename, type: @user.file.blob.content_type, disposition: 'inline'
报错undefined method 'to_blob' for #<ActiveStorage::Attached::One:0x007f8f23ca2718>
。
如何在 Active Storage 中获取实际文件作为 blob?
查看 source 的 ActiveStorage::Attached::One
似乎有一个 blob
方法,这意味着您应该可以调用:
@file.file.blob
因此,您必须使用 download
方法:
例如
send_data @file.file.download, filename: @file.file.blob.filename, type: @user.file.blob.content_type, disposition: 'inline'
我认为你现在已经解决了你的问题。
如果没有,您可以浏览 has_one_attached
和 has_many_attached
documentation 以了解如何从关系中获取 Blob – 使用 <my_relation>_blob
快捷方式。
要获得 a link for direct-download,您可以这样做:
@my_model.file_blob.service_url_for_direct_upload expires_in: 30.minutes
根据您希望系统的安全程度,您可以将此 short-living url 发送给您的 signed-in 用户,它不会暴露原始文件路径(不能 100% 确定)。
我正在构建一个 Rails 应用程序,它允许用户直接在浏览器中访问某些上传的文件,但 URL 与实际文件不同。这样可以通过强制登录来保护文件。
例如,您可以访问位于以下位置的文件:domain.com/file/19371da
过去,我是通过使用 CarrierWave 完成此操作的,然后对文件本身执行 to_blob
,然后使用 send_data
并使用数据库中存储的有关文件的数据将其发回:
send_data @file.file.to_blob, stream: false, filename: @file.name, type: @file.mime_type, disposition: 'inline'
然而,当使用新的 Active Storage 作为 CarrierWave 的潜在替代品时,我在将实际文件本身作为 blob 传递给 send_data
方法时遇到了障碍。
例如
send_data @file.file.to_blob, stream: false, filename: @file.file.blob.filename, type: @user.file.blob.content_type, disposition: 'inline'
报错undefined method 'to_blob' for #<ActiveStorage::Attached::One:0x007f8f23ca2718>
。
如何在 Active Storage 中获取实际文件作为 blob?
查看 source 的 ActiveStorage::Attached::One
似乎有一个 blob
方法,这意味着您应该可以调用:
@file.file.blob
因此,您必须使用 download
方法:
例如
send_data @file.file.download, filename: @file.file.blob.filename, type: @user.file.blob.content_type, disposition: 'inline'
我认为你现在已经解决了你的问题。
如果没有,您可以浏览 has_one_attached
和 has_many_attached
documentation 以了解如何从关系中获取 Blob – 使用 <my_relation>_blob
快捷方式。
要获得 a link for direct-download,您可以这样做:
@my_model.file_blob.service_url_for_direct_upload expires_in: 30.minutes
根据您希望系统的安全程度,您可以将此 short-living url 发送给您的 signed-in 用户,它不会暴露原始文件路径(不能 100% 确定)。