Cloudinary Blog

Direct image uploads from the browser to the cloud with jQuery

Where do you host all of your website's assets - still on your own web servers? 
In modern websites, images alone contribute to more than 50% of a website’s load time, and recent studies show that even a 1 second delay in a page's load speed can result in more than 5% loss in conversion. The impact of correctly delivering your website's images to your viewers is staggering. Luckily, Cloudinary offers a simple way to offload your website's images to the cloud, automatically transform them according to your needs and deliver them optimized through a fast CDN employing industry best practices.
In recent posts we've covered how to simply move your website's assets, either static or dynamic to Cloudinary. In this post, we wanted to detail how you can upload photos to Cloudinary directly from your users' browsers, without going through your own servers in the process. Below you will find a general explanation of our direct uploading solution, detailed integration examples and advanced tips.

Uploading images directly to the cloud

The common way of uploading images from your web application to the cloud involves a form in your application that uploads an image to your server that in turn uploads the same image to the cloud. 
While this approach works, you might want to consider a more direct approach - delivering images directly from your users' browser to the cloud without going through your intermediary server.
This approach is faster as it eliminates redundant uploads, it reduces load on your servers and it bypasses common limitations of shared web hosting (e.g. maximum size of allowed uploaded data, maximum number of concurrent requests to your application, etc.). In addition, the approach we detail below is simple to integrate with modern web browsers and includes many modern uploading UI elements such as drag & drop support, showing uploading progress, multiple file uploads support and more.

Direct uploading to Cloudinary

Cloudinary's service supports direct uploading to the cloud out-of-the-box.

The process is based on Cloudinary's jQuery plugin which in turn includes upload support based on jQuery File Upload Plugin, one of todays leading file upload solutions. Direct uploading is done using modern HTML5 cross origin resource sharing (CORS) and gracefully degrades to a seamless iframe based solution for older browsers.

To get the Cloudinary upload solution working, we will go through the following steps (detailed more granularly later on):

  • Generate an authentication signature on your server side, in your web development framework of choice.
  • Include Cloudinary's jQuery plugin.
  • Add Cloudinary’s special attributes to your file input tag in your HTML image upload form.

That’s basically it. Your visitors will now be able to upload images using drag-and-drop support (or regular browsing) and images will be uploaded directly to Cloudinary with a progress bar support.

When the upload is complete, your image's Cloudinary public ID will be added to your original form and submitted to your server. Use this public ID when you want to access the uploaded image in the future, either in its original form or after using Cloudinary's on-demand image transformations. You can also get the plugin to call a Javascript callback routine when uploading to Cloudinary is completed.

With our client libraries, setting up direct image uploads to Cloudinary is even simpler. Below are integration instructions for Ruby on Rails, Python / Django and other web dev platforms.

UPDATE - July 2014: A simpler solution for direct uploading to the cloud, without server-side signature, was introduced. See Direct upload made easy, from browser or mobile app to the cloud.


Ruby on Rails Integration

Setting up direct uploads from your Rails application is quite simple. Here is a detailed explanation: 

1. Make sure you use the latest version of Cloudinary’s Ruby GEM.

2. Place cloudinary_cors.html in the public folder of your Rails app. The file is available in the vendor/assets/html folder of the Ruby GEM.

3. Make sure to include the relevant jQuery plugins in your view. They are located in the vendor/assets/javascripts folder of the Ruby GEM.

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

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

//= require cloudinary 

4. Add the Cloudinary configuration parameters to your view:

<%= cloudinary_js_config %> 

5. Add cl_image_upload_tag to a form in your view. This tag adds a file input element that is already configured to use direct uploading. In this example, we also perform an incoming transformation (limit to 1000x1000) and add a custom class to the HTML element:

<%= form_tag(some_path, :method => :post) do  %>
  <%= cl_image_upload_tag(:image_id, :crop => :limit, :width => 1000, :height => 1000, 
                          :html => {:class => "image_upload"}) %>
<%= end %>

This is it if you use CarrierWave for managing your image uploads in your Rails application, together with Cloudinary’s plugin for CarrierWave (recommended).

Another great option is to use the Attachinary GEM developed by Milovan Zogovic. Direct uploading to Cloudinary comes out of the box with Attachinary.

If you use uploading without CarrierWave or Attachinary, one last step is required - extracting the public ID and version of the uploaded image when the form is submitted to your controller:

  if @params[:image_id].present?
     preloaded =[:image_id])
     # Verify signature by calling preloaded.valid?
     @model.image_id = preloaded.identifier

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

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


Python & Django Integration

Setting up direct uploads from your Django application is quite similar to the RoR approach. Here is a detailed explanation:

1. Make sure you use Cloudnary’s latest Python library.

2. In your Django template, load Cloudinary and include jQuery and all relevant jQuery plugins:

{% load cloudinary %}
{% load staticfiles %}
<script src="{% static "js/jquery.js" %}" type="text/javascript"></script>
{% cloudinary_includes %} 

3. Add a file uploading tag to your form:

<form action="/posts/save" method="post">
  {% csrf_token %}
  {{ form.image }}
  <input type="submit" value="Submit" />

4. Edit your and define the image form field as a CloudinaryJsFileField instance. This class does all the behind-the-scenes magic for you. In the example below, the dummy save action receives the uploaded image.

from django import forms
import cloudinary, cloudinary.uploader, cloudinary.forms

class UploadFileForm(forms.Form):
    image  = cloudinary.forms.CloudinaryJsFileField()

def save(request):
    form = UploadFileForm(request.POST)
    cloudinary.forms.cl_init_js_callbacks(form, request)
    if request.method == 'POST':
        if form.is_valid():
            image = form.cleaned_data['image']
            return HttpResponseRedirect(image.url())
    return render_to_response('posts/upload.html', 
                              RequestContext(request, {'form': form, 'post': p}))


Other development frameworks and advanced usage

In the examples above, we've shown detailed integration instructions based on Cloudinary’s Ruby and Python client libraries. The same integration concept can be used together with our PHP library using the cloudinary_js_config and cl_image_upload_tag methods.

We will soon enhance our documentation to include detailed instructions for direct Cloudinary uploads using all of our other client libraries.  

In the meantime, following are detailed instructions on how to use direct uploading in your development environment without our client libraries, using Cloudinary’s jQuery plugin directly.

1. Include jQuery and the following jQuery plugins in your HTML page:

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

2. Define your account’s Cloudinary configuration. Note that only public parameters are included (secrets must not be included in public HTML pages or client-side Javascript code):

<script type="text/javascript">

3. Add a file input field to your HTML form. 

  • Set the class name to 'cloudinary-fileupload' (alternatively, selection of input fields can be done programmatically). 
  • Set data-cloudinary-field to the name of the input field that should contain the upload reference.
  • Set data-form-data to be JSON representation of the upload API params. The mandatory fields are api_key, timestamp, signature and callback. Any additional incoming or eager transformation parameters can be specified.
    • The signature needs to be generated on the server-side for correct authentication.
    • The callback should point to a public URL of your web application that has the cloudinary_cors.html file. It is included in our jQuery plugin package and is required for iframe fallback upload.

For example:

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

The unescaped JSON content of data-form-data is:

{ "timestamp":  1345719094, 
  "callback": "",
  "signature": "7ac8c757e940d95f95495aa0f1cba89ef1a8aa7a", 
  "api_key": "1234567890" }

That's it. Image uploads by either browsing or drag-and-drop will head straight to the Cloudinary service. When done, the reference (public ID, version and signature) will be saved in the field you requested, for storing in your model at the server side. 

You can also listen to various events in your Javascript code. For example:

  • fileuploadstart - useful for showing a progress indicator when the upload starts.
  • fileuploadfail - listen to this event if you want to show an error message if an upload fails.
  • cloudinarydone - sent when upload completes. Following is a code example that displays a Cloudinary dynamically generated thumbnail of the previously uploaded image:
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  $('.preview').html(
           { format: data.result.format, version: data.result.version, 
             crop: 'scale', width: 200 }));    
  return true;


Fancy upload UI

Modern websites frequently use fancy upload widgets that include progress bars, live previews, multiple file uploads and more. The approach we’'e shown above can be easily customized and extended to feature all of these advanced capabilities. Together with Cloudinary's jQuery plugin, these great looking file upload widgets can upload your user's photos directly to Cloudinary, generate preview thumbnails on-the-fly and deliver the resulting photos from a fast CDN.

Direct uploading is a powerful feature that many of our readers requested. Try it out and tell us what you think?

If you have a cool code sample in any development framework with or without a fancy UI, share it with our community and we will give you a generous one year discount for any of Cloudinary’s paid plans.

UPDATE - July 2014: A simpler solution for direct uploading to the cloud, without server-side signature, was introduced. See Direct upload made easy, from browser or mobile app to the cloud.

Recent Blog Posts

Find images & videos with a robust new search engine

Great content is hard to come by. You can invest a lot of time and effort in building a great media library, but if content managers and editors can't quickly find what they need at the right time, it's almost useless (and frustrating). Good search capabilities allow you to provide them with a better experience: present relevant content or a well-organized catalog by a variety of criteria such as tags, folders, size, resolution, aspect ratio, faces, colors and many more.

Read more
Video at Large Scale - Contributions from the Developer Community

Video is an increasingly important component for websites - whether it’s to inform visitors, enhance user experience or support sales and marketing efforts. But delivering high-quality video at large scale can be quite a challenge. You need to consider encoding, format, bandwidth usage, delivery and the devices on which visitors may be watching the video, to name just a few concerns.

Read more

Image Optimization in WordPress

By Prosper Otemuyiwa
Image Optimization in WordPress

WordPress is the number one content management system (CMS) in use today, running approximately 27 percent of the entire internet. Several high-traffic websites run on WordPress, and many utilize media, such as images and videos, to attract users and meet their needs.


Read more

Build a Vue Watermarking App for your Image Gallery

By Christian Nwamba
Build a Vue Watermarking App for your Image Gallery

If you intend to build a photo gallery online, you have to seriously consider how to protect the images from users who are not buying them. While visitors need to see the picture before purchasing, there needs to be a way to ensure that even serious buyers are not tempted to use the images without agreeing to your license terms.

Read more

Should You Transform Images On Upload or On Demand?

By Christian Nwamba
Should You Transform Images On Upload or On Demand?

As a developer, you hope and anticipate that your website or mobile application will be accessed by different users on various devices. To improve the user-experience, irrespective of the viewing device, you need to make sure that each image adapts to different graphic layouts, device resolutions and other viewing requirements. For example, for an E-Commerce site, one image will be displayed on different pages — home page, product page, shopping cart and more — and will be viewed on a desktop, cellphone or a tablet. This means that you need to create numerous versions of every image and for a website with hundreds of images, manual manipulation is not scalable.

Read more
Introducing Website Speed Test: An Image Analysis Tool Integrated with WebPagetest

Because images dominate page weight, methodical image optimization can have a significant effect on conversions and user experience. And the performance tools you choose to use can have a powerful impact on how websites are built and maintained. One such popular open source tool is WebPagetest. It is designed to measure and analyze webpage performance, which is why Cloudinary chose to partner with our friends over there to launch Website Speed Test.

Read more