[英]What is the proper way to preview a file (image or pdf) using active storage?
我正在嘗試預覽我上傳的 PDF 文件和圖像文件:
class Document < ApplicationRecord
belongs_to :resourceable, :polymorphic => true
has_one_attached :file
end
我嘗試使用 .preview 和 .representation 方法將上傳的圖像或 pdf 的預覽顯示為縮略圖。
@document.file.preview(resize_to_limit: [100, 100])
ActiveStorage::UnpreviewableError: ActiveStorage::UnpreviewableError
>>> image_tag(@document.file.representation(resize: '500x500'))
ArgumentError: Can't resolve image into URL: undefined method `to_model' for #<ActiveStorage::Variant:0x00007fe39e809768>
document.file.representable?
和document.file.previewable?
在一些文檔中。 想知道這些方法有什么作用? 有時我可以表示為真,但可預覽為假。
從 Rails 5.2 開始, image_tag
助手要求你傳遞一個 url。 在它猜測通過什么之前。
要從您的活動存儲變體傳遞 url,請執行以下操作:
image_tag(main_app.rails_representation_url(
@document.file.variant(resize: '500x500'))
) if @document.file.attached?
根據 文檔,圖像不可預覽,PDF 是。
要檢查文檔是否有可用的預覽,請使用可預覽previewable?
方法:
image_tag(main_app.rails_representation_url(
@document.try(@document.previewable? ? :preview : :variant, resize: '500x500')
) if @document.file.attached?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.