【问题标题】:ActiveStorage 5.2.1 - uploaded asset is nil since upload has not finished. How to wait for finished upload?ActiveStorage 5.2.1 - 上传的资产为零,因为上传尚未完成。如何等待完成上传?
【发布时间】:2018-11-18 15:12:35
【问题描述】:

我将 ActiveStorage 用于用户生成的样式表,这些样式表将上传到 s3,以便将它们包含在自定义用户样式的网页中。

所以我有一个模型CustomeTheme

has_one_attached :style, dependent: :purge_later

还有一个 after_save 回调,在保存自定义样式后进行上传

self.style.attach(io: File.open(File.join(asset_path, name)), filename: name, content_type: 'text/css')

包含在布局中

= stylesheet_link_tag url_for(@custom_theme.style)

现在的问题是,用户保存样式并看到自定义网页的预览,但没有自定义样式(此时为 404),因为上传到 s3 尚未完成,至少是这样我想什么。

to_model delegated to attachment, but attachment is nil

/usr/local/bundle/gems/activesupport-5.2.1/lib/active_support/core_ext/module/delegation.rb:278:in `rescue in method_missing'
/usr/local/bundle/gems/activesupport-5.2.1/lib/active_support/core_ext/module/delegation.rb:274:in `method_missing'
/usr/local/bundle/gems/actionpack-5.2.1/lib/action_dispatch/routing/polymorphic_routes.rb:265:in `handle_model'
/usr/local/bundle/gems/actionpack-5.2.1/lib/action_dispatch/routing/polymorphic_routes.rb:280:in `handle_model_call'
/usr/local/bundle/gems/actionview-5.2.1/lib/action_view/routing_url_for.rb:117:in `url_for'

所以我仍然不清楚这个问题,我怎么知道资产(无论是样式还是图像)已准备好显示?

【问题讨论】:

  • 保存后的样式怎么用?你没有显示代码。日志显示什么?您是否看到保存后正在运行分析作业?你检查文件路径和url是否正确?
  • @arieljuod 我刚刚更新了这个问题。分析作业成功运行,上传通常成功,但为时已晚,这就是我的怀疑,因为我可以在几个请求/秒后看到样式

标签: ruby-on-rails ruby-on-rails-5 rails-activestorage


【解决方案1】:

2 种可能的方法:

  1. 为上传状态检查定义一个路由,然后在 Javascript 中运行一个间隔来检查给定上传 id 的上传状态。完成后,端点会返回资产 URL,然后您可以使用它。 (例如,如果资产是图像,那么您只需将其放在 <img> 标记 src 属性上)。

  2. 另一种方法类似于Delayed Paperclip 所做的:

在默认设置下,当您第一次上传图片并尝试在作业完成之前显示它时,Paperclip 将不明智地输出尚未处理的图片的 url,即将导致页面上显示损坏的图像链接。

要在处理图像时通过回形针输出丢失的图像 url,您只需将#{attachment_name}_processing 列添加到要启用此功能的特定模型。

class AddAvatarProcessingToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :avatar_processing, :boolean
  end

  def self.down
    remove_column :users, :avatar_processing
  end
end

@user = User.new(avatar: File.new(...))
@user.save
@user.avatar.url #=> "/images/original/missing.png"

# Process job

@user.reload
@user.avatar.url #=> "/system/images/3/original/IMG_2772.JPG?1267562148"

【讨论】:

  • 这里的轮询可能很困难,因为我没有取回活动存储上传作业ID的作业ID,对吧?!此外,这有点开销,我不希望用户轮询资产上传时间不应超过 2 秒。这就是为什么我想同步运行 custom_theme.save 并等待上传作业完成。
  • @dc10 在这种情况下,第二种方法不使用轮询。它只是在资产仍在处理时定义“missing.png”图像的路径。完成后,它将显示指向实际 URL 的链接。要直接回答您关于如何知道何时可以显示的问题:您可以致电“@user.style.processing?
猜你喜欢
  • 2018-04-08
  • 2017-07-11
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多