0
votes

I'm currently working on uploading multiple images to Cloudinary as part of a form. The problem is the Cloudinary uploader only allows uploading images 1 at a time, so the post request is extremely slow when I upload images like the following:

params[:photos].each do |_, photo|
  uploaded_photo = Cloudinary::Uploader.upload(photo.tempfile)
  photo = Photo.new(property: @property, public_id: uploaded_photo[:public_id.to_s])
  photo.save
end

The images are associated with a property, so having multiple images is very important. I've tried running the uploads in parallel with the Parallel gem, but it just caused my server to freeze up for some unknown reason.

I've also toyed with the idea of uploading images to Cloudinary as they are selected on the form, and then purging any unused images in a job at some undetermined interval.

How would you guys recommend uploading multiple images to cloudinary as part of a model?

1

1 Answers

0
votes

One approach to upload multiple files to Cloudinary is to create separate threads:

photos = [] # Array of photos to upload
threads = []
number_of_threads = 3

chunk_size = photos.size/number_of_threads
chunks = photos.each_slice(chunk_size).to_a
chunks.each do |res|
    threads << Thread.new {     
        # Add code here to do the upload to Cloudinary
    }
end
threads.each { |thr| thr.join }

You can either upload all the images to Cloudinary first and then update your model or update your model at the end of each thread. I don't see why there should be an issue there. I would not recommend more than a few threads as this could consume a majority of the resources on your server if you have many users uploading content at the same time. Alternatively, the Cloudinary site does recommend using their jQuery plugin to do multiple file uploads under their Ruby SDK docs (https://cloudinary.com/documentation/rails_image_and_video_upload#additional_jquery_library_features).