Cloudinary Blog

Direct image uploads from the browser to the cloud with jQuery

Upload Images Directly to the Cloud With Our jQuery Plugin
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.

Recent Blog Posts

10 Website Videos Mistakes and How to Solve Them

It should come as no surprise that video use on the internet is exploding. You can see the dramatic growth of video on the average site in this SpeedCurve blog post.

With the growth in video comes greater bandwidth use, which is not only costly for your IT budget, but for your visitors as well. Beyond the expense, there is the user experience to consider. The heavier the page, the longer it will take to load, and the greater likelihood visitors will abandon your site. Page load speed is also an important factor in SEO ranking, so clearly video is something we need to take seriously and get right. Video is challenging, presenting terms still unfamiliar to developers - like codecs, bitrate and adaptive bitrate streaming. As a result, mistakes are being made in video implementation.

Read more
Android Data Saver: Optimizing Mobile Data Usage with Cloudinary

Over the life of a mobile device, the cost of a cellular data plan often exceeds that of the device itself. To optimize data usage and purge useless data on their mobile devices, users can enable Data Saver from Android 7.0 (API level 24). To do so, users toggle Data Saver in quick settings under the Notification shade or under Settings > Data usage. With Data Saver enabled, apps that aren't whitelisted cannot use cellular data in the background. They are also directed to consume less data while active.

Read more
Introducing the Cloudinary Upload Widget v2

At Cloudinary, we manage the entire pipeline of media assets for thousands of customers of varying sizes from numerous verticals. Cloudinary is an end-to-end solution for all your image and video needs, including upload, storage, administration, manipulation, optimization and dynamic delivery.

Read more
Convert an Image to a 3D Canvas With Cloudinary

Note
This post was cowritten with Daniel Mendoza.
Note
This post was cowritten with Daniel Mendoza.
Note

Famed American poet Henry David Thoreau once said, “This world is but a canvas to our imagination.” And, like your imagination, the transformations you can apply to images with Cloudinary are practically endless. You can even render any flat image to appear three-dimensional and framed on a canvas.

Read more
Mobile Optimization: Optimize Your Mobile-Web User Experience

TL;DR

We live in a visual world, often while on the go, and consumers expect media-rich web content. Accordingly, the loading speed of images and videos is a big factor in user experience. To optimize customer satisfaction with your mobile content, you must focus on the quality, format, and size of your digital assets. With Cloudinary, optimization is simple, not only enhancing your mobile web and app performance, but also upping your SEO game and boosting customer experience.

Read more