【问题标题】:Save Paperclip image with Sidekiq使用 Sidekiq 保存回形针图像
【发布时间】:2018-05-14 08:32:08
【问题描述】:

我正在尝试保存 Paperclip 上传的图像,这引发了 Sidekiq 工作人员。 用户将图像选择成 image[] 并将其传递给控制器​​(作为 params[:image])。

查看:

<%= file_field_tag "image[]", type: :file, multiple: true %>

当我将它传递给另一个 var(文件)时,它在控制器中工作,但是当我将它传递给 sidekiq_worker 时,它变成了字符串的哈希

控制器:

file = params[:image]
SidekiqWorker.perform_async("import_images", file)

SidekiqWorker

def perform(type, file)
    case type
    when "import_images"
        file.each do |picture|
            puts picture.class
            puts picture.original_filename 
        end
        Product.import_images(file)
        puts "SIDEKIQ_WORKER: IMPORTING IMAGES"
    end
 end

如何传递图像哈希的哈希?或者我怎样才能实现我想做的事情?

之后,图像被处理成模型,但是hash已经变成了字符串,它不起作用。

def self.import_images(file)
file.each do |picture|
    @product = Product.where(code: File.basename(picture.original_filename, ".*"))
    if(!@product.nil?)
      @product.update(:image=> picture)
    end
  end
end

感谢您的帮助:)

【问题讨论】:

  • 抱歉,为什么要使用 sidekiq?你可以通过carrierwave上传多张图片来做到这一点,有很多关于这个的指南,你可以上传到亚马逊s3存储github.com/carrierwaveuploader/…stackoverflow.com/questions/19712816/…
  • 我正在使用 Heroku,有时应用程序超时,具体取决于上传图像的数量。我需要在第二个计划流程中使用它 我可以使用carrierwave 做到这一点吗?谢谢你:)
  • 我真的不知道。对不起。
  • 谢谢,法布里齐奥!

标签: ruby-on-rails hash paperclip sidekiq


【解决方案1】:

所以,我只是做了什么来实现它......

用户上传文件后,将文件保存在文件夹中,控制器中的变量获取每张图片的名称。

when "Import images"
  file = Array.new
  params[:image].each do |picture|
    File.open(Rails.root.join('public/system/products', 'uploaded', picture.original_filename), 'wb') do |f|
      f.write(picture.read)
    end 
    file.push picture.original_filename
  end
  SidekiqWorker.perform_async("import_images", file,0,0)
  redirect_to products_url, notice: "#{t 'controllers.products.images'}"

之后,它传递给我的 sidekiq_worker 并传递给我的模型,在那里我搜索图像并搜索代码等于图像名称的产品。处理后,删除上传图片的文件:)

def self.import_images(file)
file.each do |image|
  uploaded = open("public/system/products/uploaded/"+image)
  prd = Product.where(code: File.basename(uploaded, '.*'))
  if !prd.nil?
    prd.update(image: uploaded)
  end
  File.delete("public/system/products/uploaded/"+image)
end

结束

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多