jQuery image upload

Overview

Cloudinary is a cloud-based service that provides an end-to-end image management solution including uploads, storage, administration, image manipulation, and delivery.

As part of its service, Cloudinary provides an API for uploading images and any other kind of files to the cloud. Images uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history, utilizing Amazon's S3 service.

After you upload your images to Cloudinary, you can browse them using an API or an interactive web interface and manipulate them to reach the size and look & feel that best matches your graphic design. All uploaded images and dynamically transformed images are optimized and delivered by Cloudinary through a fast CDN with advanced caching for optimal user experience.

Cloudinary's APIs allow secure uploading images from your servers, directly from your visitors browsers or mobile applications, or fetched via remote public URLs. Comprehensive image transformations can be applied on uploaded images and you can extract images' metadata and semantic information once their upload completes.

Cloudinary's Javascript library wraps Cloudinary's upload API and simplifies the integration. Javascript methods are available for easily uploading images and raw files to the cloud. jQuery view helper methods are available for uploading images directly from a browser to Cloudinary.

This page covers common usage patterns for jQuery image upload with Cloudinary.

Upload overview

You can upload images and any other files directly from the browser to Cloudinary. Uploading is done over HTTPS using a secure protocol based on the api_key and api_secret parameters of your account.

However, Cloudinary requires upload requests to be signed with your private api_secret, which should not be exposed in public web pages. Therefore, a signature needs to be generated in your server-side application for authorizing direct uploading.

You can use Cloudinary's helper methods for generating the signature in various server frameworks:

By default, uploading is performed synchronously. Once finished, the uploaded image is immediately available for manipulation and delivery.

An upload API call returns an object with content similar to that shown in the following example:

{
 public_id: "pjxlnrigoijmmeibdi0u",
 version: 1371750447,
 signature: "bfec72b23487654e964febf8b89fe5f4ce796c8c",
 width: 864,
 height: 576,
 format: "jpg",
 resource_type: "image",
 created_at: "2013-06-20T17:47:27Z",
 bytes: 120253,
 type: "upload",
 url:
  "http://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 image as well as additional information regarding the uploaded file: The Public ID of the image (used for building viewing URLs), resource type, width and height, image format, file size in bytes, a signature for verifying the response and more.

Direct uploading from the browser

You can allow your users to upload images directly from the browser to Cloudinary instead of going through your servers. This method allows for faster uploading and better user experience. It also reduces load from your servers and reduces the complexity of your server applications.

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

Direct uploading environment setup

You can download jquery.cloudinary.js from the js folder of the GitHub project. In your HTML pages, include jquery.cloudinary.js after including the jQuery library.

<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>

You should download the following files from the js folder of the GitHub project as well. These files belong to the jQuery File Upload plugin.

jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js

Include all required jQuery files in your HTML page:

<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>

Your cloud_name account parameter is required to build image URLs. The public api_key is needed to perform direct uploading to Cloudinary (e.g., image uploads). The private api_secret parameter should not be included in your client-side HTML or Javascript code. See API, URLs and access identifiers for more details.

Setting the configuration parameters can be done either programmatically in each call to a Cloudinary method or globally using the $.cloudinary.config method.

You can find your configuration parameters in the dashboard of our Management Console.

Here's an example of setting configuration parameters globally in your Javascript code:

$.cloudinary.config({ cloud_name: 'sample', api_key: '874837483274837'})

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.

This solution requires placing cloudinary_cors.html in the public folder of your server application. This file is available in the html folder of Cloudinary's Javascript library.

Direct upload file tag

A file input tag, containing Cloudinary's upload parameters and secure signature, needs to be added to your HTML page.

The following file input tag will be automatically converted by Cloudinary's jQuery plugin to perform direct uploading to the cloud:

<input name="file" type="file" 
   class="cloudinary-fileupload" data-cloudinary-field="image_id" 
   data-form-data=" ... html-escaped JSON data ... " ></input>

The unescaped JSON content of data-form-data includes all upload parameters and the signature for authorizing upload. Here's an example:

{ 
  "timestamp":  1345719094, 
  "callback": "https://www.example.com/cloudinary_cors.html",
  "signature": "7ac8c757e940d95f95495aa0f1cba89ef1a8aa7a", 
  "api_key": "1234567890" 
}

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 server-side code and store it in your model for future use, exactly as if you're using a standard server side uploading.

Users can upload one or more images or non-image files. Alternatively, you can a specify a remote HTTP URL of images. Each image uploaded to Cloudinary is assigned a unique Public ID and is available for immediate delivery and transformation. The upload method returns a hash with content similar to that shown in the following example:

{
 public_id: "pjxlnrigoijmmeibdi0u",
 version: 1371750447,
 signature: "bfec72b23487654e964febf8b89fe5f4ce796c8c",
 width: 864,
 height: 576,
 format: "jpg",
 resource_type: "image",
 created_at: "2013-06-20T17:47:27Z",
 bytes: 120253,
 type: "upload",
 url:
  "http://res.cloudinary.com/demo/image/upload/v1371750447/pjxlnrigoijmmeibdi0u.jpg",
 secure_url:
  "https://res.cloudinary.com/demo/image/upload/v1371750447/pjxlnrigoijmmeibdi0u.jpg"
}

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:

$.cloudinary.image(response.public_id + '.jpg', { width: 120, height: 80, crop: 'fill' });

Additional direct uploading options

When uploading directly from the browser, you can still specify all the upload options available to server-side uploading. However, these options should be included in the secure signature generated on the server-side.

For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly.

{
  "eager": "c_fill,h_100,w_150|e_sharpen",
  "transformation": "c_limit,h_1000,w_1000",
  "tags": "directly_uploaded,user_uploaded",

  "api_key": "1234567890",
  "callback": "https://www.example.com/cloudinary_cors.html",
  "timestamp": 1372419182,
  "signature": "f5caf4b413d9f9a0008ba4dd42ae04eabcdb9f74"
}

All upload options described in this page can be more easily specified and signed when using our client libraries: Ruby on Rails, PHP, Django, Node.js.

Public ID

Each uploaded image is assigned with a unique identifier called Public ID. It is a URL-safe string that is used to reference the uploaded resource as well as building dynamic delivery and transformation URLs.

By default, Cloudinary generates a unique, random Public ID for each uploaded image. This identifier is returned in the public_id response parameter. In the example above, the assigned Public ID is 'pjxlnrigoijmmeibdi0u'. As a result, the URL for accessing this image via our 'demo' account is the following:

http://res.cloudinary.com/demo/image/upload/pjxlnrigoijmmeibdi0u.jpg

You can specify your own custom public ID instead of using the randomly generated one. The following example specifies 'sample_id' as the public ID:

{
  "public_id": "sample_id",        
  ...
}

Using a custom public ID is useful when you want your delivery URLs to be readable and refer to the associated entity. For example, setting the public ID to a normalized user name and identifier in your local system:

{
  "public_id": "john_doe_1001",        
  ...
}

Public IDs can be organized in folders for more structured delivery URLs. To use folders, simply separate elements in your public ID string with slashes ('/'). Here's an example:

{
  "public_id": "my_folder/my_name",        
  ...
}

As the example below shows, your public IDs can include multiple folders:

{
  "public_id": "my_folder/my_sub_folder/my_name",        
  ...
}

Set use_filename as true (or '1') to tell Cloudinary to use the original name of the uploaded image file as its Public ID. Notice that the file name will be normalized and a set of random characters will be appended to it to ensure uniqueness. This is quite useful if you want to safely reuse the filenames of files uploaded directly by your users.

{
  "use_filename": 1,        
  ...
}            
      
# Generated public ID for example: 'sample_apvz1t'

Preview thumbnail, progress indication, multiple images

Cloudinary's jQuery library also enables an enhanced uploading experience - show a progress bar, display a thumbnail of the uploaded image, drag & drop support, upload multiple files and more.

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 sample 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 track the upload progress by binding to the following events: fileuploadsend, fileuploadprogress, fileuploaddone and fileuploadfail. You can find more details and options in the documentation of jQuery-File-Upload.

The following Javascript code updates a progress bar according to the data of the fileuploadprogress event:

$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) { 
  $('.progress_bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%'); 
});

You can find some more examples as well as an upload button style customization in our Photo Album sample project for Ruby on Rails.

The file input field can be configured to support simultaneous multiple file uploading. Setting the multiple HTML parameter allows uploading multiple files. Here's an example:

<input name="file" type="file" multiple="multiple"
   class="cloudinary-fileupload" data-cloudinary-field="image_id" 
   data-form-data=" ... html-escaped JSON data ... " ></input>

For more details about direct uploading, see this blog post: Direct image uploads from the browser to the cloud with jQuery.

Incoming transformations

By default, images uploaded to Cloudinary are stored in the cloud as-is. Once safely stored in the cloud, you can generate derived images from these originals by asking Cloudinary to apply transformations and manipulations.

Sometimes you may want to normalize and transform the original images before storing them in the cloud. You can do that by applying an incoming transformation as part of the upload request.

Any image transformation parameter can be specified as options passed to the upload call. A common incoming transformation use-case is shown in the following example, namely, limit the dimensions of user uploaded images to 1000x1000:

{
  "transformation": "c_limit,h_1000,w_1000",        
  ...
}

Another example, this time performing custom coordinates cropping and forcing format conversion to PNG:

{
  "transformation": "c_crop,f_png,h_300,w_400,x_50,y_80",        
  ...
}

Named transformations as well as multiple chained transformations can be applied using the transformation parameter. The following example first limits the dimensions of an uploaded image and then adds a watermark as an overlay.

{
  "transformation": "c_limit,h_1000,w_1000/fl_relative,l_my_watermark,w_0.5",        
  ...
}

Eager transformations

Cloudinary can dynamically transform images using specially crafted transformation URLs. By default, the first time a user accesses a transformation URL, the transformed images is created on-the-fly, stored persistently in the cloud and delivered through a fast CDN with advanced caching. All subsequent accesses to the same transformation would quickly deliver a cached copy of the previously generated image via the CDN.

You can tell Cloudinary to eagerly generate one or more derived images while uploading. This approach is useful when you know in advance that certain transformed versions of your uploaded images will be required. Eagerly generated derived images are available for fast access immediately when the upload call returns.

Generating transformed images eagerly is done by specifying the `eager` upload option. This option accepts either a hash of transformation parameters or an array of transformations.

The following example eagerly generates a 150x100 face detection based thumbnail:

{
  "public_id": "eager_sample",
  "eager": "c_thumb,g_face,h_100,w_150",        
  ...
}

Now, if you embed the same transformed image in your web view, it will already be available for fast delivery. The following tag embeds the derived image from the example above:

$.cloudinary.image('eager_sample.jpg', 
                   { width: 150, height: 100, crop: 'thumb', gravity: 'face' });

The following example generates two transformed versions eagerly, one fitting image into a 100x150 PNG and another applies a named transformation.

{
  "eager": "c_fit,f_png,h_150,w_100|t_jpg_with_quality_30",        
  ...
}

You can apply an incoming transformation and generate derived images eagerly using the same upload call. The following example does that while also applying a chained transformation:

{
  "transformation": "c_limit,h_120,w_100/c_crop,h_10,w_40,x_5,y_10",
  "eager": "c_scale,w_0.2|e_hue:30",        
  ...
}

For more image transformation options in jQuery, see jQuery image manipulation.

Semantic data extraction

When you upload a resource to Cloudinary, the API call will report information about the uploaded asset: width, height, number of bytes and image format. Cloudinary supports extracting additional information from the uploaded image: Exif and IPTC camera metadata, color histogram, predominant colors and coordinates of automatically detected faces. You can ask Cloudinary for this semantic data either during the upload API call for newly uploaded images, or using our Admin API for previously uploaded images.

See Cloudinary's Admin API documentation for more details: Details of a single resource.

You can tell Cloudinary to include relevant metadata in its upload API response by setting the faces, exif, colors and image_metadata boolean parameters to true (or '1') while calling the upload API.

The following example uploads an image via a remote URL, and requests the coordinates of all detected faces in the image:

{
  "faces": 1,
  ...
}

Below you can see the faces coordinates that were included in the upload response:

{ 
  "public_id": "de9wjix4hhnqpxixq6cw",
  ...
  "faces": [ [98, 74, 61, 83], [139, 130, 52, 71] ]
}

Another example, this time requesting details about the main colors of the uploaded image. Each pair in the returned colors array includes the color name or its RGB representation and the percentage of the image comprising it.

{
  "colors": 1,
  ...
}        

# Output: 
{      
 "public_id": "jhp8mciew9rvn2vkhfcu",
 ...
 "colors": 
    [["#152E03", 7.8], ["#2E4F06", 6.3], ["#3A6604", 5.6], ["#EEF2F3", 5.2],
     ["#598504", 4.6], ["#0D1903", 4.6], ["#DCDFDB", 4.4], ["#7AA403", 3.9],
     ["#DBE98B", 3.8], ["#4C7208", 3.4], ["#8DAC30", 3.3], ["#6C9406", 3.2],
     ["#89AE07", 3.2], ["#6E912F", 3.2], ["#B0C95F", 3.1], ["#9E744E", 2.9],
     ["#CD9A6F", 2.8], ["#719357", 2.5], ["#D8B395", 2.5], ["#2C4B16", 2.3],
     ["#ACCDBC", 2.3], ["#E2E0A0", 2.3], ["#8E6437", 2.3], ["#656950", 2.1],
     ["#25370A", 2.0], ["#73A092", 1.9], ["#4E3721", 1.7], ["#A0AD9A", 1.6],
     ["#BBD259", 1.5], ["#5B602B", 1.3], ["#9CA25C", 1.2], ["#302B1E", 1.2]],
   "predominant":
    {"google":
      [["yellow", 40.1],
       ["green", 24.7],
       ["brown", 13.4],
       ["black", 12.4],
       ["teal", 9.4]]
    }
  }

You can also request Exif, IPTC, colors and faces data in a single upload call:

{
  "colors": 1,
  "exif": 1,
  "faces": 1,
  "image_metadata": 1,
  ...
}

See the following blog post for more details: API for extracting semantic image data - colors, faces, Exif data and more

Raw file uploading

Cloudinary's main strength is in managing images. However, you can still use Cloudinary to manage any other file format using the same simple APIs. You'll get your files stored in a highly available storage with automatic backups and revision control, and when accessed, have them delivered through a fast CDN. Cloudinary's jQuery plugin supports uploading non-image files by default. The upload URL is automatically configured to set the resource_type component to auto.

Non-image raw files are stored in the cloud as-is. Note that while public IDs of image files do not include the file's extension, public IDs of raw files does include the original file's extension.

Here's a sample response of a raw upload call, which is slightly different from an image upload response:

{
 "public_id": "sample_spreadsheet.xls",
 "version": 1371928603,
 "signature": "9088691a2c12802767cfa7c5e874afee72be78cd",
 "resource_type": "raw",
 "created_at": "2013-06-22T19:16:43Z",
 "bytes": 6144,
 "type": "upload",
 "url:
  "http://res.cloudinary.com/demo/raw/upload/v1371928603/sample_spreadsheet.xls",
 "secure_url"=>
  "https://res.cloudinary.com/demo/raw/upload/v1371928603/sample_spreadsheet.xls"
}

Delivery URLs of raw files are built quite similarly to those of images. Just make sure to set resource_type to raw. Here's an example:

$.cloudinary.url("sample_spreadsheet.xls", { resource_type: 'raw' });

Manage tags

Cloudinary supports assigning one or more tags to uploaded images. Tags allow you to better organize your media library.

You can use our Admin API and media library web interface for searching, listing and deleting images by tags. In addition, you can merge multiple images that share the same tag into a sprite, a multi-page PDF or an animated GIF.

See our Admin API documentation for more details regarding managing images by tags.

The following example assigned two tags while uploading.

{
  "tags": "special,for_homepage",
  ...
}

You can then use our API from your server-side code to modify the assigned tags of an already uploaded image, clear the given tag from a list of images or clear all tags from a given list of images.

Notifications and async transformations

By default, Cloudinary's upload API works synchronously. Uploaded images processed and eager transformations are generated synchronously during the upload API call.

You can tell Cloudinary to generate eager transformations in the background and send you an HTTP notification callback when the transformations are ready. You can do that by setting the eager_async parameter to true and optionally setting eager_notification_url to the URL Cloudinary should send the callback to. Here's an example:

{
  "eager": "c_thumb,g_face,h_100,w_150",
  "eager_async": 1,
  "eager_notification_url": "http://mysite/my_notification_endpoint",        
  ...
}

Cloudinary also supports webhooks. With webhooks enabled, you can get a notification to your server when an upload is completed. This is useful when you use direct image uploading from the browser and you want to be informed whenever an image is uploaded by your users. Setting the notification_url parameter tells Cloudinary to perform an asynchronous HTTP GET request to your server when the upload is complete. For example:

{
  "notification_url": "http://mysite/my_notification_endpoint",
  ...
}

See the following blog post for more details: Webhooks, upload notifications and background image processing.

Upload method parameters

For a full list of the upload method parameters, see the Upload method in the Upload API Reference.