简体   繁体   中英

Upload images to heroku through delayed_job

I'm trying to upload images to s3 bucket from Heroku using delayed job.

But it seems heroku delayed job isn't able to get the tmp image path. Please let me know what I'm doing wrong or a better approach.

Here is my code of controller:

  if @post.save
    unless @post.post_type == 0
      image_a = image_b = ''
      if item_image_params['0'][:item_type] == "A"
        image_a = item_image_params['0'][:image]
        image_b = item_image_params['1'][:image]
      else
        image_a = item_image_params['1'][:image]
        image_b = item_image_params['0'][:image]
      end
      @post.delay.save_image(image_a.path, image_b.path)
    end
  end

My model code:

  def save_image(image_a, image_b)
    items.each do |item|
      if item.item_type == "A"
        item.build_item_image.image = File.open(image_a)
      else
        item.build_item_image.image = File.open(image_b)
      end
    end
    if self.save
      File.delete(image_a) if File.exist?(image_a)
      File.delete(image_b) if File.exist?(image_b)
    end
  end

I'm getting this error in delayed:

:save_image args: - /tmp/RackMultipart20150715-3-1qoy83r.jpeg - /tmp/RackMultipart20150715-3-if712h.jpeg 
 last_error:
  "No such file or directory - /tmp/RackMultipart20150715-3-if712h.jpeg\n/app/app/models/post.rb:35:in

On line no 35 the code is:

 item.build_item_image.image = File.open(image_b)

Heroku dynos cannot access each other's local file systems. If I'm understanding correctly, you have a web dyno writing to its local file system (/tmp) and then are trying to read it from a different (worker) dyno.

You are far better off having the upload go straight to S3. I have used carrierwave_direct with good success or you can use something else or roll your own.

Uploading directly to S3 also has the advantage of not tying up your web dynos while uploads are in progress as well bypassing their timeouts. If uploads go straight to heroku and take longer than the web dyno's timeout (because the file is large or the user's connection is slow) then the upload will simply fail.

I see you have tagged this question with paperclip . You may find this article from Heroku to be useful, though it looks like it is not using the preferred approach of uploading directly to s3. This blog post has some sample code for uploading directly to s3 with paperclip.

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