使用活动存储预览文件(图像或pdf)的正确方法是什么?

时间:2019-11-23 07:34:37

标签: rails-activestorage

我正在尝试预览我上传的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. 使用representation(),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?在某些文档中。想知道这些方法做什么?有时我可以表示为true,但可以预览为false。

1 个答案:

答案 0 :(得分:0)

从Rails 5.2开始,image_tag助手需要您传递一个URL。在猜测通过什么之前。

要从您的活动存储版本中传递网址,请执行以下操作:

image_tag(main_app.rails_representation_url(
    @document.file.variant(resize: '500x500'))
) if @document.file.attached?

根据docs,图片不可预览,而PDF则无法预览。

要检查文档是否具有预览功能,请使用previewable?方法:

image_tag(main_app.rails_representation_url(
    @document.try(@document.previewable? ? :preview : :variant, resize: '500x500')
) if @document.file.attached?