Cloudinary Blog

Direct upload made easy, from browser or mobile app to the cloud

Direct image upload to the cloud made easy

Handling user uploaded images on your website can be a time consuming task. In this post, we'll show how Cloudinary's cloud-based image management service can help you turn user uploading into a lightweight operation that bypasses your servers altogether.

How do you handle user uploads today? If images are uploaded directly to your servers, this requires some heavy server-side processing, bandwidth and storage space. One way to offload images is to transfer them to cloud storage. But if you're handling the upload operation on your own servers (and then transferring them to the cloud), this is still wasteful of server resources.

A smarter option is to enable uploading of images directly from users' browsers to the cloud. In a previous post, we showed how to do this with Cloudinary's cloud-based image management solution, via our jQuery plugin. We also enable this for mobile apps via the iOS and Android SDKs. But this still requires a small server-side component to handle authentication.

Now we're happy to introduce a new option that simplifies the upload process and completely bypasses your servers - Direct unsigned upload. You can now upload directly from the browser or app to Cloudinary with no predefined authentication. Instead, upload options are controlled by centralized configuration. This is easier to implement and is more suitable for modern client-side and mobile apps with a fast, dynamic UI.

Direct unsigned uploading of images to the cloud: how it works

Cloudinary is an image management solution that allows you to upload your images to the cloud, perform powerful image manipulations on-the-fly, and deliver them to users via a fast CDN.

Previously, we required that all images uploaded are signed with your account's API secret. Now, you can call Cloudinary's upload API without signing with your API secret (we call this 'unsigned'). This allows you to perform upload directly from a browser or mobile app without going through your servers at all. For security reasons, not all upload parameters can be specified directly when performing unsigned upload calls.

First, you need to enable unsigned uploading for your Cloudinary account from the Upload Settings page. If you don't have a Cloudinary account already, you can set it up for free.

Enable unsigned upload

Enabling unsigned uploading creates an 'upload preset' with a unique name, which explicitly allows uploading of images without the API secret. The preset also defines which upload options will be applied to images that are uploaded unsigned.

You can edit the preset at any point in time, to define the parameters that will be used for all images that are uploaded unsigned from user browsers or mobile apps. Read more about upload presets in this post: Centralized control for image upload.

Now, in order to perform unsigned upload, simply call Cloudinary's upload API while setting the upload_preset parameter to the unique name. No need to set the API Key and Secret credentials of your account.

The following code samples show a direct unsigned upload API call in Objective-C for iOS, Java for Android and Ruby:

Ruby:
Copy to clipboard
Cloudinary::Uploader.unsigned_upload("sample.jpg", "zcudy0uz", :cloud_name => "demo")
iOS-ObjC:
Copy to clipboard
CLCloudinary *cloudinary = [[CLCloudinary alloc] init];
[cloudinary.config setValue:@"demo" forKey:@"cloud_name"];

NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"logo" 
  ofType:@"png"];

CLUploader* uploader = [[CLUploader alloc] init:cloudinary delegate:self];
[uploader unsignedUpload:imageFilePath uploadPreset:@"zcudy0uz" options:@{}];
Android:
Copy to clipboard
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.emptyMap());

Upload options for unsigned image uploads

The 'unsigned upload preset' discussed in the previous section globally controls all upload requests coming directly from user browsers or mobile apps, which are not signed with the account API Secret. For example, you can define via the preset that after upload, Cloudinary should eagerly generate thumbnails, mark images for moderation, detect faces, analyze colors and more - and these operations will be performed after every unsigned image upload.

In addition to these global parameters in the 'unsigned upload preset', there are certain parameters you can specify for specific unsigned upload requests: public_id to assign a unique identifier to the uploaded image (while not overwriting an existing image with the same ID), tags to add tags, folder to store the image in a folder, context key-value pairs of meta data, and face_coordinates to specify custom coordinates for incoming cropping or further thumbnail generation.

The following code samples show a more advanced example: specifying a custom public ID of user_sample_image_1002, making it possible to later access the uploaded image, and assigning a tag to simplify management of the images. In addition, we show an example of building a dynamic URL that performs an on-the-fly image manipulation: generating a 150x100 face-detection-based thumbnail of the uploaded images for embedding in your application.

Ruby:
Copy to clipboard
Cloudinary::Uploader.unsigned_upload("sample.jpg", "zcudy0uz", :cloud_name => "demo", 
  :public_id => "user_sample_image_1001", :tags => "ruby_upload")
iOS-ObjC:
Copy to clipboard
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);
  }];
Android:
Copy to clipboard
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"));

The response of the API call includes the public ID of the uploaded image, URLs for accessing the image through a CDN and additional details. Here's another example of Cloudinary's dynamic image manipulation: a 150x100 face-detection-based thumbnail of the uploaded image.

Ruby:
Copy to clipboard
cl_image_tag("user_sample_image_1001.jpg", :height=>100, :gravity=>"face", :width=>150, :crop=>"thumb")
PHP v1:
Copy to clipboard
cl_image_tag("user_sample_image_1001.jpg", array("height"=>100, "gravity"=>"face", "width"=>150, "crop"=>"thumb"))
PHP v2:
Copy to clipboard
(new ImageTag('user_sample_image_1001.jpg'))
  ->resize(Resize::thumbnail()->width(150)->height(100)
    ->gravity(Gravity::focusOn(FocusOn::face())));
Python:
Copy to clipboard
CloudinaryImage("user_sample_image_1001.jpg").image(height=100, gravity="face", width=150, crop="thumb")
Node.js:
Copy to clipboard
cloudinary.image("user_sample_image_1001.jpg", {height: 100, gravity: "face", width: 150, crop: "thumb"})
Java:
Copy to clipboard
cloudinary.url().transformation(new Transformation().height(100).gravity("face").width(150).crop("thumb")).imageTag("user_sample_image_1001.jpg");
JS:
Copy to clipboard
cloudinary.imageTag('user_sample_image_1001.jpg', {height: 100, gravity: "face", width: 150, crop: "thumb"}).toHtml();
jQuery:
Copy to clipboard
$.cloudinary.image("user_sample_image_1001.jpg", {height: 100, gravity: "face", width: 150, crop: "thumb"})
React:
Copy to clipboard
<Image publicId="user_sample_image_1001.jpg" >
  <Transformation height="100" gravity="face" width="150" crop="thumb" />
</Image>
Vue.js:
Copy to clipboard
<cld-image publicId="user_sample_image_1001.jpg" >
  <cld-transformation height="100" gravity="face" width="150" crop="thumb" />
</cld-image>
Angular:
Copy to clipboard
<cl-image public-id="user_sample_image_1001.jpg" >
  <cl-transformation height="100" gravity="face" width="150" crop="thumb">
  </cl-transformation>
</cl-image>
.NET:
Copy to clipboard
cloudinary.Api.UrlImgUp.Transform(new Transformation().Height(100).Gravity("face").Width(150).Crop("thumb")).BuildImageTag("user_sample_image_1001.jpg")
Android:
Copy to clipboard
MediaManager.get().url().transformation(new Transformation().height(100).gravity("face").width(150).crop("thumb")).generate("user_sample_image_1001.jpg");
iOS:
Copy to clipboard
imageView.cldSetImage(cloudinary.createUrl().setTransformation(CLDTransformation().setHeight(100).setGravity("face").setWidth(150).setCrop("thumb")).generate("user_sample_image_1001.jpg")!, cloudinary: cloudinary)
Face detection based thumbnail

Direct uploading from the browser using jQuery

Cloudinary's jQuery plugin allows you to easily add an upload control to your web site, which allows to directly upload an image from their browsers to the cloud. Now you can use dynamic Javascript code to add direct upload controls to your rich client-side web application.

First, include Cloudinary's jQuery plugin and all dependent Javascript files (if you use our server-side client libraries for rendering your pages, there are helper methods for including all required JS files).

Copy to clipboard
<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>

Now you can use the unsigned_upload_tag method to create a new tag specifying an unsigned direct upload. You need to specify the cloud name of your Cloudinary account and the unique name of an unsigned upload preset defined in your account.

Copy to clipboard
$('.upload_form').append($.cloudinary.unsigned_upload_tag("zcudy0uz", 
  { cloud_name: 'demo' }));

Direct uploading is initiated automatically after a file is selected or dragged. An input field is automatically added to your form with the identifier of the uploaded image for referencing in your model.

Further upload options can be specified, and you can bind to upload progress and completion events, to update your application and UI accordingly. In addition, you can transform an existing input file field into an unsigned direct upload widget.

Update (08/17): Make sure your input field includes the name="file" and type="file" attributes.

The following sample Javascript code demonstrates these options. When an 'upload completed' call is received, it dynamically adds an image tag to the page, with a dynamically-generated 150x100 face-detection based thumbnail of the uploaded image, while applying a saturation increase effect.

Copy to clipboard
$('.upload_field').unsigned_cloudinary_upload("zcudy0uz", 
  { cloud_name: 'demo', tags: 'browser_uploads' }, 
  { multiple: true }
).bind('cloudinarydone', function(e, data) {

  $('.thumbnails').append($.cloudinary.image(data.result.public_id, 
    { format: 'jpg', width: 150, height: 100, 
      crop: 'thumb', gravity: 'face', effect: 'saturation:50' } ))}

).bind('cloudinaryprogress', function(e, data) { 

  $('.progress_bar').css('width', 
    Math.round((data.loaded * 100.0) / data.total) + '%'); 

});

Direct uploading from the browser uses modern cross-origin resource sharing (CORS) methods. In order to support old Internet Explorer browsers, you should place cloudinary_cors.html in the root of your web application (or set the callback upload parameter to the correct relative path or URL of this file in your web site).

Server-side upload tag rendering

When we introduced signed direct uploading from the browser a while ago, we added view helper methods for rendering direct file upload input fields from the server-side code of your favorite development frameworks.

If your web pages are rendered on the server-side and you still wish to support unsigned uploads, you can use the following new view helper methods for Ruby on Rails, PHP, Java and Node.js:

Ruby:
Copy to clipboard
cl_unsigned_image_upload_tag(:photo, "zcudy0uz", :cloud_name => "demo", 
  :tags => "test_upload")
PHP:
Copy to clipboard
<?php echo cl_unsigned_image_upload_tag('zcudy0uz', 
    $upload_preset, array("cloud_name" => "demo", "tags" => "test_upload")); ?>
Node.js:
Copy to clipboard
cloudinary.uploader.unsigned_image_upload_tag('photo', 'zcudy0uz', 
  { cloud_name: 'demo', tags: 'test_upload' });
Java:
Copy to clipboard
cloudinary.uploader().unsignedImageUploadTag("image_id", zcudy0uz, 
  Cloudinary.asMap("tags", "test_upload"), Map<String, Object> htmlOptions);

cloudinary.uploader().imageUploadTag("image_id", options, htmlOptions);

Sample client-side web projects

We've updated the sample projects of Cloudinary's client libraries (Ruby on Rails, PHP,  Django, Java) to demonstrate unsigned direct uploading with server-side rendering of the initial upload control.

In addition, to demonstrate direct unsigned uploading in client-side-only apps, we've build a sample photo album project in AngularJS. Our project uses the jQuery plugin to perform direct uploading to Cloudinary, and then uses Cloudinary to list uploaded images, further manipulate images, and deliver them via a fast CDN.

The Angular sample project is available as an open source GitHub project.

Summary

Direct uploading to the cloud from a browser or mobile app is very powerful. Unsigned uploading makes this much simpler to use in modern apps, while security measures are taken to detect and prevent abuse attempts.

This means that Cloudinary takes care of the entire image management flow - simply call the upload API from your mobile app, or include a single jQuery line in your web app, and images are uploaded directly to Cloudinary. No need for a server-side component at all, you can control upload options using presets from a centralized location, and then dynamically manipulate your images and deliver them from a fast CDN, using nothing but client-side code.

Direct uploading from the browser is one of Cloudinary's most popular features. However, the need to generate server-side signature made usage a bit more complex, especially for modern, dynamic, client-side apps. With our new unsigned upload support, and the new utility methods of the jQuery plugin and other frameworks, we believe direct upload has become much simpler, and you should definitely try it out. Any feedback will be appreciated!

Recent Blog Posts

Generate Waveform Images from Audio with Cloudinary

This is a reposting of an article written by David Walsh. Check out his blog HERE!
I've been working a lot with visualizations lately, which is a far cry from your normal webpage element interaction coding; you need advanced geometry knowledge, render and performance knowledge, and much more. It's been a great learning experience but it can be challenging and isn't always an interest of all web developers. That's why we use apps and services specializing in complex tasks like Cloudinary: we need it done quickly and by a tool written by an expert.

Read more
Make All Images on Your Website Responsive in 3 Easy Steps

Images are crucial to website performance, but most still don't implement responsive images. It’s not just about fitting an image on the screen, but also making the the image size relatively rational to the device. The srcset and sizes options, which are your best hit are hard to implement. Cloudinary provides an easier way, which we will discuss in this article.

Read more

The Future of Audio and Video on the Web

By Prosper Otemuyiwa
The Future of Audio and Video on the Web

Web sites and platforms are becoming increasingly media-rich. Today, approximately 62 percent of internet traffic is made up of images, with audio and video constituting a growing percentage of the bytes.

Read more

Embed Images in Email Campaigns at Scale

By Sourav Kundu
Embed Images in Email Campaigns at Scale

tl;dr

Cloudinary is a powerful image hosting solution for email marketing campaigns of any size. With features such as advanced image optimization and on-the-fly image transformation, backed by a global CDN, Cloudinary provides the base for a seamless user experience in your email campaigns leading to increased conversion and performance.

Read more
Build the Back-End For Your Own Instagram-style App with Cloudinary

Github Repo

Managing media files (processing, storage and manipulation) is one of the biggest challenges we encounter as practical developers. These challenges include:

A great service called Cloudinary can help us overcome many of these challenges. Together with Cloudinary, let's work on solutions to these challenges and hopefully have a simpler mental model towards media management.

Read more

Build A Miniflix in 10 Minutes

By Prosper Otemuyiwa
Build A Miniflix in 10 Minutes

Developers are constantly faced with challenges of building complex products every single day. And there are constraints on the time needed to build out the features of these products.

Engineering and Product managers want to beat deadlines for projects daily. CEOs want to roll out new products as fast as possible. Entrepreneurs need their MVPs like yesterday. With this in mind, what should developers do?

Read more