Rails image and video upload

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. Ruby methods are available for easily uploading resources 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 upload with Cloudinary.

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

Upload widget

Cloudinary's 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 code, eliminating the need to develop in-house interactive upload capabilities. See the Upload widget documentation for detailed information.

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 account's api_key and api_secret parameters.

Rails image upload

The following Ruby method uploads an image to the cloud:

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

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

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 base-64 data URI, or an FTP URL. For details, see Data upload options.

For details on all available upload options and parameters, see the Upload images and Upload videos 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 20MB).

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.

Cloudinary::Uploader.upload_large("dog.mp4", :resource_type => :video,
    :public_id => "my_folder/my_sub_folder/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 => "http://mysite/notify_endpoint")
)

Upload response

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

{
  "public_id" => "pjxlnrigoijmmeibdi0u",
  "version" => 1371750447,
  "signature" => "bfec72b23487654e964febf8b89fe5f4ce796c8c",
  "width" => 864,
  "height" => 576,
  "format" => "jpg",
  "resource_type" => "image",
  "created_at" => "2017-06-20T17:47:27Z",
  "bytes" => 120253,
  "type" => "upload",
  "url" => "https://res.cloudinary.com/demo/image/upload/v1371750447/pjxlnrigoijmmeibdi0u.jpg",
  "secure_url"=> "https://res.cloudinary.com/demo/image/upload/v1371750447/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 Upload Images and Upload Videos 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 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.

Uploading directly from the browser is done using Cloudinary's jQuery plugin. To ensure that all uploads were authorized by your application, a secure signature must first be generated in your server-side Rails code.

Direct uploading environment setup

Start by including the required Javascript files: Cloudinary's jQuery plugin as well as the jQuery-File-Upload plugin it depends on. These are located in the vendor/assets/javascripts/cloudinary folder of the Ruby GEM.

You can directly include the Javascript files:

<%= javascript_include_tag("jquery.ui.widget", "jquery.iframe-transport", 
        "jquery.fileupload", "jquery.cloudinary") %>

Alternatively, If you use Asset Pipeline, edit your application.js and add the following line:

//= require cloudinary

Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters.

Important
Never expose your api_secret in public client-side code.

To automatically set-up Cloudinary's configuration, include the following line in your view or layout:

<%= cloudinary_js_config %>

The Cloudinary jQuery library utilizes the Blueimp File Upload library to support uploading media directly from the browser. You must explicitly initialize this library:

$(function() {
  if($.fn.cloudinary_fileupload !== undefined) {
    $("input.cloudinary-fileupload[type=file]").cloudinary_fileupload();
  }
});

Tip

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. To support older browsers that do not support CORS, the jQuery plugin gracefully degrades to an iframe based solution. This solution requires placing cloudinary_cors.html in the public folder of your Rails application. This file is available in the vendor/assets/html folder of the Ruby GEM.

Direct upload file tag

Embed a file input tag in your HTML pages using one of the following methods:

  • cl_image_upload_tag: images
  • cl_upload_tag: images or videos
  • cl_image_upload images in Rails form builders
  • cl_upload images or videos in Rails form builders

Directly uploading an image

The following example adds a file input field for images to your form. Selecting or dragging a file to this input field automatically initiates uploading from the browser to Cloudinary.

<%= form_tag(some_path, :method => :post) do  %>
  <%= cl_image_upload_tag(:image_id) %>
  ...
<% end %>

Here's another example that includes more upload parameters. This call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.

<%= cl_image_upload_tag(
  :image_id,
  :tags => "directly_uploaded",
  :crop => :limit, :width => 1000, :height => 1000,
  :eager => [{ :crop => :fill, :width => 150, :height => 100 }],
  :html => { :style => "margin-top: 30px" }  
) %>

When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field of your selected name (e.g., 'image_id' in the example above).

You can then process the identifier received by your Rails controller and store it in your model for future use, exactly as if you're using a standard server side uploading.

The following Rails controller code processes the received identifier, verifies the signature (concatenated to the identifier) and updates a model entity with the identifiers of the uploaded image (i.e., the Public ID and version of the image).

if params[:image_id].present?
  preloaded = Cloudinary::PreloadedFile.new(params[:image_id])         
  raise "Invalid upload signature" if !preloaded.valid?
  @model.image_id = preloaded.identifier
end

Having stored the image_id, you can now display a directly uploaded image in the same way you would display any other Cloudinary hosted image:

<%= cl_image_tag(@model.image_id, :crop => :fill, :width => 120, :height => 80) %>

Directly uploading a video

The following example renders a direct file upload input field using the cl_upload_tag helper method. Although the default resource_type for this method is auto, the video type is explicitly defined, and asynchronous eager transformations are used to generate adaptive bitrate streaming content. The html parameter is used to include standard HTML parameters (in this case, an id attribute) in the generated tag.

cl_upload_tag(:video_id, :resource_type => "video", 
  :eager => [{:streaming_profile => "full_hd", :format => "m3u8"}], 
  :eager_async => true, 
  :eager_notification_url => "http://mysite/notify_endpoint", 
  :html => {:id => "my_upload_tag"})

Additional jQuery library features

Cloudinary's jQuery library also enables an enhanced uploading experience with options like showing a progress bar, displaying a thumbnail of the uploaded image, drag & drop support, uploading multiple files and more.

For example, bind to Cloudinary's cloudinarydone event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin. The following code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.

$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  
  $('.preview').html(
    $.cloudinary.image(data.result.public_id, 
      { format: data.result.format, version: data.result.version, 
        crop: 'fill', width: 150, height: 100 })
  );    
  $('.image_public_id').val(data.result.public_id);    
  return true;
});

You can find more details and options in the jQuery documentation.

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:

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:

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 a 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 Upload Images and Upload Videos 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.