Cloudinary Image Uploader

By (Sponsor)  on  

Over the past months I've detailed how developers can complete a variety of tasks using Cloudinary, an image (and audio and video) hosting, delivery, and transformation provider.  Cloudinary’s client-side integration libraries and SDKs simplify the integration with your development platform of choice: Ruby on Rails, PHP, Node.js, Angular, .NET, Python & Django, jQuery, Java, Scala, Android, iOS and more. Once you've signed up for a Cloudinary account, you can upload your images using one of their many APIs, but today I'm going to introduce you to their Image Uploader -- a method for uploading media from any user directly to Cloudinary, thus bypassing your own servers which can lighten performance and save you time!

Setup

Start by logging into your account (or signing up!), visiting the Settings page, and click "Enable unsigned uploading".

Cloudinary Unsigned Upload

An upload preset string will be provided to you, allowing you to upload images to Cloudinary without exposing your API key.

jQuery Image Uploader

Cloudinary allows developers to upload user-provided (or "unsigned", since the accountholder isn't uploading) images directly to Cloudinary -- no need to have your server handle any of it.  Cloudinary provides a jQuery plugin for all of this work, so add those JavaScript resources to the 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>

A $.cloudinary object is added to jQuery which contains a host of useful methods for retrieving and even sending images to Cloudinary; to send uploads to Cloudinary from the client side, first append Cloudinary's upload widget to your form:

$('#upload_form').append(
    // First the "upload preset string", then your cloud name
    $.cloudinary.unsigned_upload_tag('zcudy0uz', { cloud_name: 'demo' })
);

Upload is triggered after a file has been selected (or dragged).  An input field is automatically added to your form whose value identifies the uploaded image for referencing in your other code.  You will also be provided cloudinarydone and cloudinaryprogress events during the stages of the upload, a la:

/*
    Events!
        - Update a progress bar upon "cloudinaryprogress" event
        - Add new thumbnail image to gallery when complete!
*/
$('.upload_field').unsigned_cloudinary_upload('zcudy0uz', 
  { cloud_name: 'demo', tags: 'browser_uploads' }, 
  { multiple: true }
)
.bind('cloudinaryprogress', function(e, data) { 
  $('.progress_bar').css('width', 
    Math.round((data.loaded * 100.0) / data.total) + '%'); 
})
.bind('cloudinarydone', function(e, data) {
  // Image upload complete!  Add it to gallery with nice animation!
  $('.thumbnails').append($.cloudinary.image(data.result.public_id, 
    { format: 'jpg', width: 150, height: 100, 
      crop: 'thumb', gravity: 'face', effect: 'saturation:50' } ))}
);
cyber

Cloudinary's CORS settings allow for the cross-origin upload and the image uploader supports all major browsers! If you'd like to see the image uploader in action, check out this sample photo album project.

Uploading to Cloudinary within Native Mobile OS

If you provide a mobile app, whether for iOS or Android, you can also use Cloudinary's API for unsigned image uploads:

Android

InputStream getAssetStream(String filename) throws IOException {
  return getInstrumentation().getContext().getAssets().open(filename);
}

Map config = new HashMap();
config.put("cloud_name", "demo");
Cloudinary cloudinary = new Cloudinary(config);

cloudinary.uploader().unsignedUpload(getAssetStream("sample.jpg"), "zcudy0uz", 
  Cloudinary.asMap("public_id", "user_sample_image_1001", "tags", "android_upload"));

iOS

NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];

[uploader unsignedUpload:imageData uploadPreset:@"zcudy0uz" options:[NSDictionary dictionaryWithObjectsAndKeys:@"user_sample_image_1002", @"public_id", @"tags", @"ios_upload", nil] withCompletion:^(NSDictionary *successResult, NSString *errorResult, NSInteger code, id context) {

    if (successResult) {

      NSString* publicId = [successResult valueForKey:@"public_id"];
      NSLog(@"Upload success. Public ID=%@, Full result=%@", publicId, successResult);
      CLTransformation *transformation = [CLTransformation transformation];
      [transformation setWidthWithInt: 150];
      [transformation setHeightWithInt: 100];
      [transformation setCrop: @"fill"];
      [transformation setGravity:@"face"];
                
      NSLog(@"Result: %@", [cloudinary url:publicId options:@{@"transformation": transformation, @"format": @"jpg"}]);                

    } else {

      NSLog(@"Upload error: %@, %d", errorResult, code);            

    }

  } andProgress:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite, id context) {
    NSLog(@"Upload progress: %d/%d (+%d)", totalBytesWritten, totalBytesExpectedToWrite, bytesWritten);
  }];

Cloudinary has you covered for bulk image upload on both the web, server, and mobile device front -- a complete provider!

User-provided content, especially in the case of media, can be difficult to handle.  Whether it's storage, delivery, or optimization, handling these on your own can be a disaster; multiple services, security, optimization, hosting, etc.  Cloudinary, with their flexible APIs, can help.  Check out Cloudinary today!

Discussion

  1. Simon Davies

    Great little article, but is there a vanilla JS version as well?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!