我正在构建一个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形式获取实际文件?
发布于 2018-01-12 01:53:08
因此,要执行此操作,您必须使用download方法:
例如:
send_data @file.file.download, filename: @file.file.blob.filename, type: @user.file.blob.content_type, disposition: 'inline'发布于 2018-01-11 23:59:58
查看ActiveStorage::Attached::One的source,它看起来像是有一个blob方法,这意味着您应该能够调用:
@file.file.blob发布于 2018-03-27 18:58:21
我想你现在已经解决了你的问题。如果没有,你可以通过has_one_attached和has_many_attached documentation来了解如何使用<my_relation>_blob快捷方式从关系中获取Blob。
要获取a link for direct-download,您可以执行以下操作:
@my_model.file_blob.service_url_for_direct_upload expires_in: 30.minutes根据你希望你的系统有多安全,你可以把这个短暂的url发送给你的登录用户,它不会暴露原始的文件路径(不是100%确定的)。
https://stackoverflow.com/questions/48211124
复制相似问题