Cloudinary Blog
Learn more...

Direct image uploads from the browser to the cloud with jQuery

Aug 28, 2012 by Nadav Soferman
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 = Cloudinary::PreloadedFile.new(params[:image_id])
     # Verify signature by calling 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 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" />
</form> 

4. Edit your views.py 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">
   $.cloudinary.config({"api_key":"1234567890","cloud_name":"demo"});
</script> 

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": "https://www.example.com/cloudinary_cors.html",
  "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(
       $.cloudinary.image(data.result.public_id, 
           { format: data.result.format, version: data.result.version, 
             crop: 'scale', width: 200 }));    
       $('.image_public_id').val(data.result.public_id);    
  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.

blog comments powered by Disqus