【问题标题】:What is the proper way to preview a file (image or pdf) using active storage?使用活动存储预览文件(图像或 pdf)的正确方法是什么?
【发布时间】:2019-11-23 07:34:37
【问题描述】:

我正在尝试预览我上传的 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。

【问题讨论】:

    标签: rails-activestorage


    【解决方案1】:

    从 Rails 5.2 开始,image_tag 助手要求你传递一个 url。在它猜测通过了什么之前。

    要从您的活动存储变体中传递 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?
    

    【讨论】:

      猜你喜欢
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2019-11-21
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多