繁体   English   中英

使用Sidekiq保存回形针图像

[英]Save Paperclip image with Sidekiq

我正在尝试保存回形针上传的图像并抛出Sidekiq工人。 用户将图像选择为image []并将其传递给控制器​​(作为params [:image])。

视图:

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

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

控制器:

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

Sidekiq工人

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

如何传递图像哈希的哈希? 或者我该如何实现自己的目标?

在那之后,图像被处理成一个模型,但是散列已经变成一个字符串,并且不起作用。

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

谢谢您的帮助 :)

所以,我所做的只是为了实现它...

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

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

结束

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM