gpt4 book ai didi

rails-activestorage - 使用事件存储预览文件(图像或 pdf)的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-05 07:16:52 25 4
gpt4 key购买 nike

我正在尝试预览我上传的 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? 在某些文档中。想知道这些方法有什么作用?有时我可以表示为真,但可预览为假。

最佳答案

从 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?

关于rails-activestorage - 使用事件存储预览文件(图像或 pdf)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59005518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com