简体   繁体   中英

Save Paperclip image with Sidekiq

I'm trying to save the Paperclip uploaded images throw a Sidekiq worker. The user select the images into a image[] and passes it to the controller (as params[:image]).

View:

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

When I pass it to another var (files), it works in the controller, but when I pass it to the sidekiq_worker, it turns into a hash of strings

Controller:

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

How can I pass a hash of image-hashes? Or how can I achieve what I want to do?

After that, the images are processed into a model, but the hash already turned into a string and it does not works.

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

Thank you for your help :)

So, what I just did to make it happen...

After the user uploaded the files, it saves them in a folder and a variable in controller gets the name of each image.

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'}"

After that, it passes to my sidekiq_worker and passes to my model, where I search for the image and search for the product where the code equals the name of the image. After processing, deletes the file of the uploaded image :)

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

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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