Ruby/Rails image and video upload

Last updated: Dec-18-2022

Cloudinary provides an API for uploading images, videos, and any other kind of file to the cloud. Files uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history. Cloudinary's APIs allow secure uploading from your servers, directly from your visitors' browsers or mobile applications, or fetched via remote public URLs.

Cloudinary's Ruby gem wraps Cloudinary's upload API and simplifies the integration. Methods are available for easily performing Rails image and video uploads to the cloud. Rails view helper methods are available for uploading directly from a browser to Cloudinary. Additionally, if you already have a live application with a large media collection, you can use the Cloudinary Ruby migration tool to automate the upload of all your media assets to Cloudinary.

This page covers common usage patterns for Rails image and video upload with Cloudinary.

For details on all available upload options and parameters, see the Media upload documentation, and the upload method of the Upload API Reference.

Tip
Cloudinary's Upload widget provides an alternative to using a Cloudinary SDK to add upload functionality to your application, eliminating the need to develop in-house interactive upload capabilities. The upload widget is an interactive, feature rich, simple-to-integrate user interface that enables you to add Cloudinary upload support to your website. The widget can be easily embedded in your web application with just a few lines of JavaScript code. See the Upload widget documentation for detailed information.

Upload widget main screen

Server-side upload

You can upload images, video (or any other raw file) to Cloudinary from your Ruby code or Ruby on Rails server. Uploading is done over HTTPS using a secure protocol based on your product environment's api_key and api_secret parameters.

Rails image upload

The following Ruby method uploads an image to the cloud:

Copy to clipboard
Cloudinary::Uploader.upload(file, options = {})

For example, uploading a local image file named 'my_image.jpg':

Copy to clipboard
Cloudinary::Uploader.upload('my_image.jpg')

The file to upload can be specified as a local path, a remote HTTP or HTTPS URL, a whitelisted storage bucket (S3 or Google Storage) URL, a base64 data URI, or an FTP URL. For details, see File source options.

For details on all available upload options and parameters, see the Media upload documentation, and the upload method of the Upload API Reference.

Rails video upload

You upload videos in exactly the same way as images. However, the upload method supports uploading files only up to 100 MB. To upload larger videos, use the upload_large method, which uploads large files to the cloud in chunks.

The upload_large method has the identical signature and options as the upload method, with the addition of an optional chunk_size parameter (default 20 MB).

The following example uploads dog.mp4 to Cloudinary and stores it in a bi-level folder structure with the public ID dog_closeup. It also performs two eager transformations that resize the video to a square and a small rectangle.

Copy to clipboard
Cloudinary::Uploader.upload_large("dog.mp4", :resource_type => :video,
    :public_id => "myfolder/mysubfolder/dog_closeup",
    :chunk_size => 6_000_000
    :eager => [
      {:width => 300, :height => 300, :crop => :pad, :audio_codec => :none}, 
      {:width => 160, :height => 100, :crop => :crop, :gravity => :south, :audio_codec => :none }], 
    :eager_async => true, 
    :eager_notification_url => "https://mysite.example.com/notify_endpoint")
)

Upload response

By default, uploading is performed synchronously. Once finished, the uploaded image or video is immediately available for transformation and delivery. An upload call returns a Hash with content similar to the following:

Copy to clipboard
{
  "asset_id" => "b5d6f12112dcae41c7293ce3a984d304",
  "public_id" => "pjxlnrigoijmmeibdi0u",
  "version" => 1571218850,
  "signature" => "bfec72b23487654e964febf8b89fe5f4ce796c8c",
  "width" => 864,
  "height" => 576,
  "format" => "jpg",
  "resource_type" => "image",
  "created_at" => "2017-06-20T17:47:27Z",
  "bytes" => 120253,
  "type" => "upload",
  "url" => "http://res.cloudinary.com/demo/image/upload/v1571218850/pjxlnrigoijmmeibdi0u.jpg",
  "secure_url"=> "https://res.cloudinary.com/demo/image/upload/v1571218850/pjxlnrigoijmmeibdi0u.jpg"
}

The response includes HTTP and HTTPS URLs for accessing the uploaded media asset as well as additional information regarding the uploaded asset: The Public ID, resource type, width and height, file format, file size in bytes, a signature for verifying the response and more.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the upload method of the Upload API Reference.

Direct uploading from the browser

The upload sample mentioned above allows your server-side Ruby code to upload media assets to Cloudinary. In this flow, if you have a web form that allows your users to upload images or videos, the media file's data is first sent to your server and only then uploaded to Cloudinary.

A more efficient and powerful option is to allow your users to upload images and videos in your client-side code directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and a better user experience. It also reduces load from your servers and reduces the complexity of your Rails applications.

You can upload directly from the browser using signed or unsigned calls to the upload endpoint, as shown in the Upload multiple files using a form examples.

For signed uploads from your client-side code, a secure signature must be generated in your server-side Rails code. You can use the api_sign_request method to generate SHA signatures:

Copy to clipboard
Cloudinary::Utils.api_sign_request(params_to_sign, api_secret)

Migrating assets to Cloudinary

If your web application is already live in production with many media assets already uploaded and stored somewhere, you can use the Cloudinary migration tool for Ruby. This tool allows you to manage the migration process: upload all resources to Cloudinary, perform the uploading quickly using multiple worker threads, handle communication errors, and allow pausing and resuming the migration process at any time. In order to use the migration tool, you need to install the sqlite3 Ruby gem (gem install sqlite3), in addition to the Cloudinary gem.

The following is an example of migration code that migrates all resources of the Post entities that are stored in a database:

Copy to clipboard
require 'cloudinary/migrator'

migrator = Cloudinary::Migrator.new(
  :retrieve=>proc{|id| Post.find(id).data }, 
  :complete=>proc{|id, result| $stderr.print "done \#{id} \#{result}\n" }
  )

Post.find_each(:conditions=>["id > ?", migrator.max_given_id], :select => "id") do
  |post|
  migrator.process(:id => post.id, :public_id => "post_\#{post.id}")
end
migrator.done

When constructing the Migrator object you can provide the following parameters:

  • :retrieve - A method that is called on a given ID you recognize. It must return the asset to upload in one of the following formats:
    • A public HTTP URL
    • The actual content of the asset
    • An IO stream for reading the asset's content
    • An ActiveRecord::Base instance
    • A Cloudinary::CarrierWave instance
  • :complete - A callback method that is called when a asset was successfully uploaded. The method receives the internal ID of the asset and the result returned from the server (that includes the Public ID and the version).
  • :threads (Optional) - Number of worker threads to run simultaneously. An integer value between 1 and 100. Default: 10
  • :debug (Optional) - Print debugging information while migrating assets. Default: false.
  • :api_key and :api_secret unless they are configured in cloudinary.yml.

Tip
If you want to use multiple upload threads and you fetch your assets with a database using Rails connections, make sure that the database connection pool size is at least number-of-threads+1. To ensure this, edit config/database.yml and add the following line to the file:

Copy to clipboard
pool: 12

You need to feed the migrator with assets to upload. This is done by calling the process method, which adds the received asset details to a persistent queue. The process method accepts the following parameters:

  • :id - An internal ID for recognizing your assets during the migration process.
  • :public_id (Optional) - A Cloudinary public ID to assign to a asset. If not specified, a random public ID is generated.
  • :url (Optional) - A public HTTP URL of an image. If specified, you don't have to provide the :retrieve method to the migration constructor.
  • Additional upload parameters (Optional) - You can specify additional standard upload parameters to send to Cloudinary while uploading the asset, such as tags, transformation instructions, and eager transformations. For the full list of available upload parameters, see the upload method of the Upload API Reference.

Related topics

  • For more information on uploading media assets, see the Media upload documentation.
  • For details on all available upload parameters, see the upload method of the Upload API Reference.
  • Seamless signature verification and model integration can also be automatically handled by Cloudinary's plugin for CarrierWave. For details, see Rails & CarrierWave integration.
  • You may also want to take a look at Attachinary. Attachinary offers direct uploading to Cloudinary, out-of-the-box.

✔️ Feedback sent!

Rate this page: