簡體   English   中英

使用活動存儲預覽文件(圖像或 pdf)的正確方法是什么?

[英]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 的預覽顯示為縮略圖。

  1. 使用 preview() 會導致以下錯誤:
@document.file.preview(resize_to_limit: [100, 100])

ActiveStorage::UnpreviewableError: ActiveStorage::UnpreviewableError
  1. 使用表示(),image_tag 無法從 ActiveStorage::Variant 對象解析圖像 url,導致以下錯誤:
>>> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM