我知道ActiveStorageurl_for(user.avatar)
方法。例:
<%= link_to "Download this file", url_for(@user.avatar) %>
很好,但是看起来好像没有授权建立。知道此链接的任何人都可以下载此文档。
过去,当我使用paperclip时,我有一个指向自定义控制器操作的链接。该自定义控制器操作完成了授权,如果一切正常,那么我曾经send_file
将文件发送给用户。就像这样:
def deliver_the_file
authorize :my_authorization
send_file @user.avatar.path
end
如何使用active_storage执行此操作?我要做的就是url_for
完全不授权用户的实现。
我正在特别关注ActiveStorage上《 Rails指南》的“下载文件”部分。
相关示例代码:
# model
class Book < ApplicationRecord
has_one_attached :book_cover
end
class BooksController < ApplicationController
...
# custom action to authorize and then deliver the active_storage file
def deliver_it
# ... assume authorization already happened
send_file rails_blob_path(@book.book_cover, disposition: "attachment")
end
end
出现错误并说:
无法读取文件
我也尝试过这样:
def deliver_it
# ... assume authorization already happened
send_file @book.book_cover.download
end
这返回了错误:
字符串包含空字节
我也尝试过这样:
def deliver_it
@book.book_cover.download
end
这返回了错误:
BooksController#deliver_it缺少此请求的模板
我也尝试过这个:
def deliver_it
send_file @book.book_cover.blob
end
出现错误并说:
没有将ActiveStorage :: Blob隐式转换为String
最好的选择是使用ActiveStorage::Blob#service_url
重定向到Blob的签名的短期URL:
class Books::CoversController < ApplicationController
before_action :set_active_storage_host, :set_book
def show
redirect_to @book.cover.service_url
end
private
def set_active_storage_host
ActiveStorage::Current.host = request.base_url
end
def set_book
@book = Current.person.books.find(params[:book_id])
end
end
或者,您自己提供文件。您可以ActionController::Live
用来将文件流式传输到客户端,而不必一次将整个文件读入内存。
class Books::CoversController < ApplicationController
include ActionController::Live
before_action :set_book
def show
response.headers["Content-Type"] = @book.cover.content_type
response.headers["Content-Disposition"] = "attachment; #{@book.cover.filename.parameters}"
@book.cover.download do |chunk|
response.stream.write(chunk)
end
ensure
response.stream.close
end
# ...
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句