【问题标题】:Rails Delayed Job, add image upload to delayed job taskRails 延迟作业,添加图片上传到延迟作业任务
【发布时间】:2022-01-02 20:18:34
【问题描述】:

我有一个简单的 Rails 应用程序,它使用 ActiveStorage 将照片上传到对象。

class ProjectAsset < ApplicationRecord
  belongs_to :project
  belongs_to :user

  has_one_attached :asset 

  has_many :comments, dependent: :delete_all
  accepts_nested_attributes_for :comments
  
  #DB columns => :project_id :asset :user_id
end

并将它们存储在 AWS S3 上:

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

amazon:
  service: S3
  access_key_id: ***
  secret_access_key: *** 
  region: ***
  bucket: ***

我有一个简单的表格:

<%= form_for ProjectAsset.new do |form| %>
  <%= form.hidden_field :project_id, :value => @project.id %>
  <%= form.hidden_field :user_id, :value => current_user.id %>
  <%= form.file_field :asset, multiple: false, direct_upload: true, class: "", onchange: "autoUpload(this);" %>
              
  <%= form.submit 'Add this Photo' %>
       
<% end %>
    

这会保存图像并自动重定向到适当的视图模板。

def create
    @project_asset = ProjectAsset.new(project_asset_params)

    respond_to do |format|
      if @project_asset.save
        format.html { redirect_to project_path(@project_asset.project), notice: "Project asset was successfully created." }
        format.json { render :show, status: :created, location: @project_asset }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @project_asset.errors, status: :unprocessable_entity }
      end
    end
  end

我的问题是这样的,它有点像两个部分。

  1. 如何将:create 上上传的图像 (:asset) 放在 Delayed::Job 队列中,然后保存其余记录并继续重定向? 和
  2. 重定向后,图像显示在视图模板上。如果有足够快的数据传输,这很好,但如果你在 wifi 之外,那就是一场噩梦。在资产完全上传到 S3 之前,如何将 storage 中的用户本地图像用作图像?

【问题讨论】:

    标签: ruby-on-rails delayed-job rails-activestorage


    【解决方案1】:
    1. 您很可能无法将 S3 上传委托给后台作业,因为它无法访问 Web 服务器的临时存储,并且您可能不希望将二进制数据作为字符串传递到参数中,这可能会导致内存问题。最常见的解决方案是使用“直接上传”功能,让您的浏览器上传到 S3,而 rails 应用程序仅在上传后接收其路径。有关详细信息,请参阅https://edgeguides.rubyonrails.org/active_storage_overview.html#direct-uploads
    2. 默认情况下,上传的图像不会存储在本地存储中,这可能会有所帮助:How to save an image to localStorage and display it on the next page?

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 2013-11-26
      • 2012-04-20
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2011-12-14
      • 2022-11-10
      相关资源
      最近更新 更多