Node.js image upload


Cloudinary is a cloud-based service that provides an end-to-end image and video management solution including uploads, storage, administration, manipulation, and delivery.

As part of its service, Cloudinary provides an API for uploading images, videos, and any other kind of file to the cloud. Images uploaded to Cloudinary are stored safely in the cloud with secure backups and revision history, utilizing Amazon's S3 service.

After you upload your media assets to Cloudinary, you can browse them using an API or an interactive web interface and manipulate them to reach the size and look & feel that best matches your graphic design. All uploaded media resources as well as dynamically transformed resources are optimized and delivered by Cloudinary through a fast CDN with advanced caching for optimal user experience.

Cloudinary's APIs allow secure uploading from your servers, directly from your visitors browsers or mobile applications, or fetched via remote public URLs. Comprehensive transformations can be applied on uploaded resources and you can extract image and video metadata and semantic information once their upload is complete.

Cloudinary's Javascript module wraps Cloudinary's upload API and simplifies the integration. Javascript methods are available for easily uploading resources to the cloud. Node.js view helper methods are available for uploading directly from a browser to Cloudinary.

This page covers common usage patterns for Node.js image upload with Cloudinary.

Server side upload

You can upload images (or any other raw file) to Cloudinary from your Node.js. Uploading is done over HTTPS using a secure protocol based on your account's api_key and api_secret parameters.

The following Javascript method uploads an image to the cloud:

function upload(file, options, callback)

For example, uploading a local image file named my_image.jpg:

    function(error, result) {console.log(result, error)});

For a full list of the upload method parameters, see the Upload method in the Upload API Reference.

By default, uploading is performed synchronously. Once finished, the uploaded image is immediately available for manipulation and delivery.

An upload API call returns a Hash with content similar to that shown in the following example:

  public_id: 'cr4mxeqx5zb8rlakpfkg',
  version: 1372275963,
  signature: '63bfbca643baa9c86b7d2921d776628ac83a1b6e',
  width: 864,
  height: 576,
  format: 'jpg',
  resource_type: 'image',
  created_at: '2017-06-26T19:46:03Z',
  bytes: 120253,
  type: 'upload',
  url: '',
  secure_url: '' 

The response includes HTTP and HTTPS URLs for accessing the uploaded image as well as additional information regarding the uploaded file: The Public ID of the image (used for building viewing URLs), resource type, width and height, image format, file size in bytes, a signature for verifying the response and more.

Public ID

Each uploaded image is assigned with a unique identifier called Public ID. It is a URL-safe string that is used to reference the uploaded resource as well as building dynamic delivery and transformation URLs.

By default, Cloudinary generates a unique, random Public ID for each uploaded image. This identifier is returned in the public_id response parameter. In the example above, the assigned Public ID is 'c87hg9xfxrd4itiim3t0'. As a result, the URL for accessing this image via our 'demo' account is the following:

You can specify your own custom public ID instead of using the randomly generated one. The following example specifies 'sample_id' as the public ID:

cloudinary.v2.uploader.upload('my_image.jpg', {public_id: "sample_id"}, 
    function(error, result){console.log(result, error)});

Using a custom public ID is useful when you want your delivery URLs to be readable and refer to the associated entity. For example, setting the public ID to a normalized user name and identifier in your local system:

cloudinary.v2.uploader.upload('my_image.jpg', {public_id: "john_doe_1001"},
    function(error, result){console.log(result, error)});

Public IDs can be organized in folders for more structured delivery URLs. To use folders, simply separate elements in your public ID string with slashes ('/'). Here's an example:

cloudinary.v2.uploader.upload('my_image.jpg', {public_id: "my_folder/my_name"},
    function(error, result){console.log(result, error)});

As the example below shows, your public IDs can include multiple folders:

cloudinary.v2.uploader.upload('my_image.jpg', {public_id: "my_folder/my_sub_folder/my_name"},
    function(error, result){console.log(result, error)});

Set use_filename as true to tell Cloudinary to use the original name of the uploaded image file as its Public ID. Notice that the file name will be normalized and a set of random characters will be appended to it to ensure uniqueness. This is quite useful if you want to safely reuse the filenames of files uploaded directly by your users.

cloudinary.v2.uploader.upload('sample.jpg', {use_filename: true},
    function(error, result){console.log(result, error)});

# Generated public ID for example: 'sample_apvz1t'

Data uploading options

Cloudinary's Node module supports uploading files from a local file path, an input data stream or buffer, the remote FTP, HTTP or HTTPS URL address of an existing file, or an S3 URL of a whitelisted bucket.

To upload an image by specifying the local path:

    function(error, result){console.log(result, error)});

If your images are already publicly available online, you can specify their remote HTTP URLs instead of uploading the actual data. In this case, Cloudinary will fetch the image from its remote URL for you. This option allows for a much faster migration of your existing images. Here's an example:

    function(error, result){console.log(result, error)});

If you have existing images in an Amazon S3 bucket, you can point Cloudinary to their S3 URLs. Note - this option requires a quick manual setup. Contact us and we'll guide you on how to allow Cloudinary access to your relevant S3 buckets.

    function(error, result){console.log(result, error)});

In cases where images are uploaded by users of your Node.js application through a web form, you can pass the temporary path of the req.files variable:

    function(error, result){console.log(result, error)});

You can use cloudinary.upload_stream to write to the uploader as a stream:

var fs = require('fs');
var stream = cloudinary.v2.uploader.upload_stream(function(error, result){console.log(result, error)});
var file_reader = fs.createReadStream('my_picture.jpg').pipe(stream)

Or you can upload a file from a buffer and store it in `raw` format:

cloudinary.v2.uploader.upload_stream({resource_type: 'raw'}, 
    function(error, result){console.log(result, error)})

Direct uploading from the browser

The upload samples mentioned above allows your server-side Node code to upload images to Cloudinary. In this flow, if you have a web form that allows your users to upload images, the image data is first sent to your server and only then uploaded to Cloudinary.

A more efficient and powerful option is to allow your users to upload images directly from the browser to Cloudinary using jQuery instead of going through your servers. This method allows for faster uploading and better user experience. It also reduces load from your servers and reduces the complexity of your Node.js applications.

Uploading directly from the browser is done using Cloudinary's jQuery plugin. To ensure that all uploads were authorized by your application, a secure signature must first be generated in your server-side Node.js code.

Direct uploading environment setup

Start by including the required Javascript files - jQuery, Cloudinary's plugin and the jQuery-File-Upload plugin it depends on. These are available in the js folder of Cloudinary's Javascript library.

You can directly include the Javascript files:

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery.iframe-transport.js"></script>
<script type="text/javascript" src="jquery.fileupload.js"></script>
<script type="text/javascript" src="jquery.cloudinary.js"></script>

Cloudinary's jQuery plugin requires your cloud_name and additional configuration parameters to be available. Note: never expose your api_secret in public client side code.

To automatically set-up Cloudinary's configuration, include the following line in your view or layout:


The Cloudinary JavaScript library utilizes the Blueimp File Upload library to support uploading media directly from the browser. You must explicitly initialize this library:

$(function() {
  if($.fn.cloudinary_fileupload !== undefined) {

Direct uploading from the browser is performed using XHR (Ajax XMLHttpRequest‎) CORS (Cross Origin Resource Sharing) requests. In order to support older browsers that do not support CORS, the jQuery plugin will gracefully degrade to an iframe based solution.

This solution requires placing cloudinary_cors.html in the static folder of your Node application. This file is available in the html folder of Cloudinary's Javascript library. The following code builds a URL of the local cloudinary_cors.html file:

var cloudinary_cors = "https://" + + "/cloudinary_cors.html";

Direct upload file tag

Embed a file input tag in your HTML pages using the image_upload_tag view helper method.

The following example adds a file input field to your form. Selecting or dragging a file to this input field will automatically initiate uploading from the browser to Cloudinary.

cloudinary.v2.uploader.image_upload_tag('image_id', {callback: cloudinary_cors});

When uploading is completed, the identifier of the uploaded image is set as the value of a hidden input field of your selected name (e.g., image_id in the example above).

You can then process the identifier received by your Node.js code and store it in your model for future use, exactly as if you're using a standard server side uploading.

The following Javascript code processes the received identifier, verifies the signature (concatenated to the identifier) and updates a model entity with the identifiers of the uploaded image (i.e., the Public ID and version of the image).

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

var preloaded_file = new cloudinary.PreloadedFile(query.image_id);
if (preloaded_file.is_valid()) {
  photo.image_id = preloaded_file.identifier();
} else {
  throw("Invalid upload signature");

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

cloudinary.image(photo.public_id, { format: "jpg", crop: "fill", width: 120, height: 80 });

Additional direct uploading options

When uploading directly from the browser, you can still specify all the upload options available to server-side uploading.

For example, the following call performs direct uploading that will also tag the uploaded image, limit its size to given dimensions and generate a thumbnail eagerly. Also notice the custom HTML attributes.

cloudinary.v2.uploader.image_upload_tag('image_id', {
    callback: cloudinary_cors,
    tags: "directly_uploaded",
    crop: "limit", width: 1000, height: 1000,
    eager: { crop: "fill", width: 150, height: 100 },
    html: { style: "margin-top: 30px" }

For the full list of parameters available for signed uploads, see the Upload method in the Upload API Reference.

Note: For security reasons, only this limited set of parameters can be used in an unsigned upload request.

Preview thumbnail, progress indication, multiple images

Cloudinary's jQuery library also enables an enhanced uploading experience - show a progress bar, display a thumbnail of the uploaded image, drag & drop support, upload multiple files and more.

Bind to Cloudinary's cloudinarydone event if you want to be notified when an upload to Cloudinary has completed. You will have access to the full details of the uploaded image and you can display a cloud-generated thumbnail of the uploaded images using Cloudinary's jQuery plugin.

The following sample code creates a 150x100 thumbnail of an uploaded image and updates an input field with the public ID of this image.

$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  
      { format: data.result.format, version: data.result.version, 
        crop: 'fill', width: 150, height: 100 })
  return true;

You can track the upload progress by binding to the following events: fileuploadsend, fileuploadprogress, fileuploaddone and fileuploadfail. You can find more details and options in the documentation of jQuery-File-Upload.

The following Javascript code updates a progress bar according to the data of the fileuploadprogress event:

$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) { 
  $('.progress_bar').css('width', Math.round((data.loaded * 100.0) / + '%'); 

You can find some more examples as well as an upload button style customization in our Photo Album sample project.

The file input field can be configured to support simultaneous multiple file uploading. Setting the multiple HTML parameter to true allows uploading multiple files. Note - currently, only a single input field is updated with the identifier of the uploaded image. You should manually bind to the cloudinarydone event to handle results of multiple uploads. Here's an example:

cloudinary.v2.uploader.image_upload_tag('image_id', { html: { multiple: 1 } });

For more details about direct uploading, see this blog post: Direct image uploads from the browser to the cloud with jQuery.

Incoming transformations

By default, images uploaded to Cloudinary are stored in the cloud as-is. Once safely stored in the cloud, you can generate derived images from these originals by asking Cloudinary to apply transformations and manipulations.

Sometimes you may want to normalize and transform the original images before storing them in the cloud. You can do that by applying an incoming transformation as part of the upload request.

Any image transformation parameter can be specified as options passed to the upload call. A common incoming transformation use-case is shown in the following example, namely, limit the dimensions of user uploaded images to 1000x1000:

cloudinary.v2.uploader.upload('/home/my_image.jpg', {width: 1000, height: 1000, crop: "limit"},
    function(error, result) {console.log(result, error)});

Another example, this time performing custom coordinates cropping and forcing format conversion to PNG:

    {width: 400, height: 300, x: 50, y: 80, crop: "crop", format: "png" },
    function(error, result) {console.log(result, error)});

Named transformations as well as multiple chained transformations can be applied using the transformation parameter. The following example first limits the dimensions of an uploaded image and then adds a watermark as an overlay.

    {transformation: [
       {width: 1000, height: 1000, crop: "limit" },
       {overlay: "my_watermark", flags: "relative", width: 0.5}]},
    function(error, result) {console.log(result, error)});

Eager transformations

Cloudinary can dynamically transform images using specially crafted transformation URLs. By default, the first time a user accesses a transformation URL, the transformed images is created on-the-fly, stored persistently in the cloud and delivered through a fast CDN with advanced caching. All subsequent accesses to the same transformation would quickly deliver a cached copy of the previously generated image via the CDN.

You can tell Cloudinary to eagerly generate one or more derived images while uploading. This approach is useful when you know in advance that certain transformed versions of your uploaded images will be required. Eagerly generated derived images are available for fast access immediately when the upload call returns.

Generating transformed images eagerly is done by specifying the `eager` upload option. This option accepts either a hash of transformation parameters or an array of transformations.

The following example eagerly generates a 150x100 face detection based thumbnail:

    {public_id: "eager_sample", eager: {
        width: 150, height: 100, crop: "thumb", gravity: "face"}}, 
    function(error, result) {console.log(result, error)});

Now, if you embed the same transformed image in your web view, it will already be available for fast delivery. The following tag embeds the derived image from the example above:

    {width: 150, height: 100, crop: "thumb", gravity: "face"});

The following example generates two transformed versions eagerly, one fitting image into a 100x150 PNG and another applies a named transformation.

    {eager: [
      {width: 100, height: 150, crop: "fit", format: "png"}, 
      {transformation: "jpg_with_quality_30"}]},
    function(error, result) {console.log(result, error)});

You can apply an incoming transformation and generate derived images eagerly using the same upload call. The following example does that while also applying a chained transformation:

    {transformation: [
      {width: 100, height: 120, crop: "limit"}, 
      {crop: "crop", x: 5, y: 10, width: 40, height: 10}],
     eager: [
      {width: 0.2, crop: "scale"}, 
      {effect: "hue:30"}]},
    function(error, result) {console.log(result, error)});

For more image transformation options in Node.js, see Node.js image manipulation.

Semantic data extraction

When you upload a resource to Cloudinary, the API call will report information about the uploaded asset: width, height, number of bytes and image format. Cloudinary supports extracting additional information from the uploaded image: Exif and IPTC camera metadata, color histogram, predominant colors and coordinates of automatically detected faces. You can ask Cloudinary for this semantic data either during the upload API call for newly uploaded images, or using our Admin API for previously uploaded images.

See Cloudinary's Admin API documentation for more details: Details of a single resource.

You can tell Cloudinary to include relevant metadata in its upload API response by setting the faces, exif, colors and image_metadata boolean parameters to true while calling the upload API.

The following example uploads an image via a remote URL, and requests the coordinates of all detected faces in the image:

    {faces: true}, function(error, result) {console.log(result, error)});

Below you can see the faces coordinates that were included in the upload response:

  public_id: 'r0mvyp87fxkcd4romveg',
  faces: [ [ 98, 74, 61, 83 ], [ 139, 130, 52, 71 ] ] 

Another example, this time requesting details about the main colors of the uploaded image. Each pair in the returned colors array includes the color name or its RGB representation and the percentage of the image comprising it.

    {colors: true}, function(error, result) {console.log(result, error)});  

# Output: 
  public_id: 'vowvhxynrtuzclouvafy',
   [ [ '#152E02', 7.9 ], [ '#2E4F06', 6.3 ], [ '#3A6604', 5.6 ], [ '#EEF2F3', 5.2 ],
     [ '#598504', 4.6 ], [ '#0D1903', 4.6 ], [ '#DCDFDB', 4.4 ], [ '#7AA403', 3.9 ],
     [ '#DBE98A', 3.8 ], [ '#4C7208', 3.5 ], [ '#8DAC30', 3.3 ], [ '#6C9406', 3.2 ], 
     [ '#6E912F', 3.2 ], [ '#B0C95F', 3.1 ], [ '#89AF07', 3.1 ], [ '#9E744E', 2.9 ],
     [ '#CD9A6F', 2.8 ], [ '#D8B395', 2.5 ], [ '#719357', 2.4 ], [ '#ACCDBC', 2.3 ],
     [ '#8E6437', 2.3 ], [ '#E2E0A0', 2.3 ], [ '#2C4B16', 2.3 ], [ '#656950', 2.1 ],
     [ '#25370A', 2 ], [ '#73A092', 1.9 ], [ '#4E3721', 1.6 ], [ '#A0AD9A', 1.6 ],
     [ '#BBD258', 1.5 ], [ '#5B602B', 1.3 ], [ '#302B1D', 1.3 ], [ '#9CA25C', 1.2 ] ],
  predominant: { 
      [ [ 'yellow', 40.1 ],
        [ 'green', 24.6 ],
        [ 'brown', 13.4 ],
        [ 'black', 12.5 ],
        [ 'teal', 9.4 ] ] 

You can also request Exif, IPTC, colors and faces data in a single upload call:

    {faces: true, exif: true, colors: true, image_metadata: true},
    function(error, result) {console.log(result, error)});

See the following blog post for more details: API for extracting semantic image data - colors, faces, Exif data and more

Raw file uploading

Cloudinary's main strength is in managing images. However, you can still use Cloudinary to manage any other file format using the same simple APIs. You'll get your files stored in a highly available storage with automatic backups and revision control, and when accessed, have them delivered through a fast CDN.

You can upload a raw file to Cloudinary by setting the resource_type parameter to raw.

    {public_id: "sample_spreadsheet", resource_type: "raw"},
    function(error, result) {console.log(result, error)});

Non-image raw files are stored in the cloud as-is. Note that while public IDs of image files do not include the file's extension, public IDs of raw files does include the original file's extension.

Here's a sample response of a raw upload call, which is slightly different from an image upload response:

  public_id: 'sample_spreadsheet.xls',
  version: 1372279007,
  signature: 'c56aabe3f9c7aefd3e50a877c2d17b3d381b5a53',
  resource_type: 'raw',
  created_at: '2017-06-23T14:55:21Z',
  bytes: 6144,
  type: 'upload',
  url: '',
  secure_url: '' 

Sometimes you don't know whether your users would upload image files or raw files. In order to support that, you can set the resource_type parameter to auto. Cloudinary will automatically detect whether the uploaded file is an image or a non-image raw file. When using direct image uploading from the browser, resource type is set to auto by default.

    {resource_type: "auto"}, function(error, result) {console.log(result, error)});

Delivery URLs of raw files are built quite similarly to those of images. Just make sure to set resource_type to raw. Here's an example:

cloudinary.url("sample_spreadsheet.xls", {resource_type: "raw"})

Update and delete images

Image uploaded to Cloudinary are stored persistently in the cloud. You can programatically delete an uploaded image using the following method:

function destroy(public_id, options, callback)

For example, the following code would delete the uploaded image assigned with the public ID 'zombie':

cloudinary.v2.uploader.destroy('zombie', function(error, result){console.log(result, error)});

See our Admin API documentation for more options of listing and deleting images and files.

When you delete an uploaded image, all its derived images are deleted as well. However, images and derived images that were already delivered to your users might have cached copies at the CDN layer. If you now upload a new image with the same public ID, the cached copy might be returned instead. To avoid that, use different randomly generated public IDs for each upload or alternatively, add the version component to the delivery URLs. If none of these solutions work, you might want to force cache invalidation for each deleted image.

Forcing cache invalidation is done by setting the invalidate parameter to true either when deleting an image or uploading a new one. Note that it usually takes up to one hour for the CDN invalidation to take effect. Here's are two examples:

    {invalidate: true }, function(error, result) {console.log(result, error)});
    {public_id: "zombie", invalidate: true},
    function(error, result) {console.log(result, error)});

Refresh images

Cloudinary supports forcing the refresh of Facebook & Twitter profile pictures, using the explicit API method. The response of this method includes the image's version. Use this version to bypass previously cached CDN copies. For Facebook pictures, use the application-specific numeric ID only.

    {type: "facebook"}, function(error, result) {console.log(result, error)});

You can also use the explicit API call to generate transformed versions of an uploaded image. This is useful when Strict Transformations are allowed for your account and you wish to create custom derived images for already uploaded images.

    {type: "upload", eager: {width: 150, height: 230, crop: "fill"}},
    function(error, result) {console.log(result, error)});

Rename images

You can rename images uploaded to Cloudinary. Renaming means changing the public ID of already uploaded images. The following method allows renaming a public ID:

function rename(from_public_id, to_public_id, options, callback)

For example, renaming an image with the public ID 'old_name' ro 'new_name':

cloudinary.v2.uploader.rename('old_name', 'new_name')

By default, Cloudinary prevents renaming to an already taken public ID. You can set the overwrite option to true to delete the image that has the target public ID and replace it with the image being renamed:

cloudinary.v2.uploader.rename('old_name', 'new_name', { overwrite: true });

Manage tags

Cloudinary supports assigning one or more tags to uploaded images. Tags allow you to better organize your media library.

You can use our Admin API and media library web interface for searching, listing and deleting images by tags. In addition, you can merge multiple images that share the same tag into a sprite, a multi-page PDF or an animated GIF.

See our Admin API documentation for more details regarding managing images by tags.

The following example assigned two tags while uploading.

    {public_id: "sample_id", tags: ['special', 'for_homepage']},
    function(error, result) {console.log(result, error)});

You can modify the assigned tags of an already uploaded image. The following example assigns a tag to a list of images:

    ['sample_id', 'de9wjix4hhnqpxixq6cw'],
    function(error, result) {console.log(result, error)});

The following example clears the given tag from a list of images:

    ['sample_id', 'de9wjix4hhnqpxixq6cw'],
    function(error, result) {console.log(result, error)});

This example clears all tags from a given list of images:

cloudinary.v2.uploader.replace_tag('another_tag', 'sample_id',
    function(error, result) {console.log(result, error)});

Text creation

Cloudinary allows generating dynamic text overlays with your custom text. First you need to create a text style - font family, size, color, etc. The name of the text style is its public ID and it behaves like an image of the text type.

The following command creates a text style named dark_name of a certain font, color and style:

cloudinary.v2.uploader.text("Sample Name", 
    {public_id: "dark_name", font_family: "Arial", font_size: 12, font_color: "black", opacity: 90},
    function(error, result) {console.log(result, error)});

The following image tag adds a text overlay using the created dark_name text style.

    {overlay: "text:dark_name:Hello+World", gravity: "south_east", x: 5, y: 5});

For more text style options, see Text layers creation.

More information about text overlays is available in our adding text overlays in Node.js documentation.

Notifications and async transformations

By default, Cloudinary's upload API works synchronously. Uploaded images processed and eager transformations are generated synchronously during the upload API call.

You can tell Cloudinary to generate eager transformations in the background and send you an HTTP notification callback when the transformations are ready. You can do that by setting the eager_async parameter to true and optionally setting eager_notification_url to the URL Cloudinary should send the callback to. Here's an example:

      {width: 150, height: 100, crop: "thumb", gravity: "face"},
      eager_async: true, 
      eager_notification_url: "https://mysite/my_notification_endpoint"},
    function(error, result) {console.log(result, error)}));

Cloudinary also supports webhooks. With webhooks enabled, you can get a notification to your server when an upload is completed. This is useful when you use direct image uploading from the browser and you want to be informed whenever an image is uploaded by your users. Setting the notification_url parameter tells Cloudinary to perform an asynchronous HTTP GET request to your server when the upload is complete. For example:

    {notification_url: "https://mysite/my_notification_endpoint"},
    function(error, result) {console.log(result, error)})

See the following blog post for more details: Webhooks, upload notifications and background image processing.

Upload method parameters

function upload(file, options, callback)

For a full list of the upload method parameters, see the Upload method in the Upload API Reference.