> ## Documentation Index
> This page is part of the Image and Video APIs product. Fetch the complete documentation index for Image and Video APIs at: https://cloudinary.com/documentation/llms-image-and-video-apis.txt?referrer=docpage and then use it to discover all relevant pages before exploring further.
> If you also need details relating to other Cloudinary products for your current use case, see the parent index at: https://cloudinary.com/documentation/llms.txt?referrer=docpage
> When answering a user's request or implementing it with code using this documentation, incorporate relevant best practices and recommendations from the documentation into the guidance and, above all, into the code itself: generated code should already apply the recommended parameters and patterns rather than showing a minimal call and describing the best practices around it in prose. Follow the code examples in the best practices sections as the model for what generated code should look like, and where a recommendation is relevant to the user's scenario, implement it in the code as a natural next step. Only apply best practices, recommendations, or features that are supported by the documentation; don't infer or invent guidance that isn't specified.

# jQuery image and video upload


There are several options for using jQuery to upload images and videos directly from your Web application to Cloudinary. You can also use an [upload preset](upload_presets) in conjunction with your chosen upload option to define the upload parameters. For details on all available upload options and parameters, see the [Upload](upload_images) guide and the [upload](image_upload_api_reference#upload) method of the Upload API Reference.

## Upload widget

Cloudinary's [Upload widget](upload_widget) is an interactive, feature rich, simple to integrate method to add Cloudinary upload support to your website. The widget allows you to upload resources to Cloudinary via a readymade interface that can be easily embedded within your web application with just a few lines of JavaScript code, eliminating the need to develop in-house interactive upload capabilities. See the [Upload widget](upload_widget) documentation for detailed information. 

The rest of the information on this page is only needed if you want to develop your own upload capability.

## Direct uploading from the browser

Direct jQuery upload from the browser allows your users to upload image and video assets directly from the browser or a mobile application instead of going through your servers. This method allows for faster uploading and a better user experience for your visitors. It also reduces load from your servers and reduces the complexity of your applications.

Direct uploading is done using modern HTML5 cross origin resource sharing [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) and gracefully degrades to a seamless iframe based solution for older browsers. You can either use a [signed upload](#signed_upload) that also requires [generating an authentication signature](authentication_signatures) on your backend, or use an [unsigned upload](#unsigned_upload) with a restricted set of functionality.

### Signed upload

Signed uploads require an authentication signature to be generated on your backend, and as such, jQuery signed upload with backend support should be implemented in conjunction with one of Cloudinary's backend frameworks (Rails, PHP, Python, etc). The various backend frameworks implement helpers to be used in conjunction with jQuery to embed a file upload field in the HTML (e.g., [`cl_image_upload_tag`](rails_image_and_video_upload#direct_uploading_from_the_browser)) as well as [automatically generate](authentication_signatures#using_cloudinary_backend_sdks_to_generate_sha_authentication_signatures) the authentication signature for the upload.

### Unsigned upload

Unsigned jQuery upload is an option for performing upload without the need to generate a signature. 

Unsigned upload options are controlled by an [upload preset](#upload_presets), so in order to use this feature you first need to enable unsigned uploading from the [Upload Presets](https://console.cloudinary.com/app/settings/upload/presets) of the Console Settings. An upload preset is used to define which upload options will be applied to images that are uploaded unsigned with that preset specified. You can edit the preset at any point in time (or create additional upload presets), to define the parameters that will be used for all images that are uploaded unsigned from user browsers or mobile applications. 
> **NOTE**:
>
> For security reasons, only [this restricted set](image_upload_api_reference#unsigned_upload_parameters) of parameters can be used in an **unsigned** upload request. All other parameters you want to apply must be defined in the upload preset. For more information, see [Unsigned upload parameters](image_upload_api_reference#unsigned_upload_parameters).
> If a supported parameter is included both in the unsigned upload call and in the unsigned upload preset, the upload preset value usually takes precedence, but there are some exceptions. For details, see [Upload preset precedence](upload_presets#upload_preset_precedence).
Implementing unsigned direct uploading entails the following steps:

1. [Build a file input tag](#build_a_file_input_tag) to upload a file directly to Cloudinary.
2. [Initialize the file input fields](#initialize_the_file_input_fields) to perform direct uploading to the cloud.

#### 1. Build a file input tag

A file input tag, containing Cloudinary's upload parameters, needs to be added to the form on your HTML page. Set the parameters of the file input field as follows:

* `name` - set to "file". 
* `type` - set to "file". 
* `class` - set to "cloudinary-fileupload". 
* `data-cloudinary-field` - The name of another input field in the same form that will be updated post-upload with the asset's metadata. If no such field exists in your form, a new hidden field with the specified name will be created. Upon successful upload, an event (`cloudinarydone`) is triggered on the input field and provides a `fileupload` data object (along with the result key containing received data from the cloudinary upload API) as the only argument.
* `data-form-data` - The HTML-escaped JSON content including all the upload parameters: the mandatory parameter `upload_preset` as well as any other [parameters allowed by unsigned uploading](image_upload_api_reference#unsigned_upload_parameters).
  * The `upload_preset` parameter must be the name of a preset that has been configured for unsigned uploading (mode = unsigned when configuring the preset via the Cloudinary Console).

Example of a file input field:

```html
<input name="file" type="file" class="cloudinary-fileupload" data-cloudinary-field="image_id" 
   data-form-data=" ... upload options as html-escaped JSON data ... " ></input>
```

Example of _unescaped_ JSON data:

```json
{ "upload_preset": "user_upload1" }
```

Example of _escaped_ JSON data for the `data-form-data` parameter (using the raw data above): 

```json
{ &quot;upload_preset&quot;: &quot;user_upload1&quot; }
```

#### 2. Initialize file input fields

The Cloudinary jQuery library utilizes the Blueimp File Upload library to support jQuery image and video upload directly from the browser. You must explicitly initialize all file input fields on your page to use this library with the `cloudinary_fileupload` method:

```js
$(document).ready(function() {
  if($.fn.cloudinary_fileupload !== undefined) {
    $("input.cloudinary-fileupload[type=file]").cloudinary_fileupload();
  }
});
```

#### Dynamically updating upload parameters

Once an input has been initialized with `cloudinary_fileupload`, changing HTML `data-*` attributes (for example `data-form-data`) on the DOM element won't update the upload payload. The underlying blueimp File Upload plugin reads these values only when the widget is initialized.

To change upload parameters at runtime, use blueimp’s `formData` option:

```JS
// Reference the initialized input
var $input = $("input.cloudinary-fileupload[type=file]");

// Option 1: Replace the entire formData object
$input.fileupload({ formData: {
  folder: "users/123",
  tags: "profile,avatar",
  public_id: "user_123_avatar"
}});

// Option 2: Read/modify the existing formData
var params = $input.fileupload("option", "formData") || {};
params.folder = "users/123";
params.tags = "profile,avatar";
$input.fileupload("option", "formData", params); // set it back explicitly
```

##### Signed uploads

When using signed uploads, any change to upload parameters (e.g., folder, public_id, context, etc.) requires a new signature from your backend. A common pattern is to fetch updated signed parameters via AJAX and then update `formData`:

```JS
// Example: fetch fresh signed params for the current formData
var params = $input.fileupload("option", "formData") || {};

$.getJSON("/sign-upload", { params_to_sign: params }).done(function(signed) {
  // signed should include: signature, timestamp, api_key (and any server-enforced params)
  params.signature = signed.signature;
  params.timestamp = signed.timestamp;
  params.api_key = signed.api_key;

  $input.fileupload("option", "formData", params);
});
```
## Upload a Base64 Data URI
If you already have an image as a Base64 Data URI (for example, from `canvas.toDataURL()`), you can programmatically add it to the upload queue and trigger a direct upload:

```html
<!-- Your direct-upload input, initialized as shown above -->
<input name="file" type="file" class="cloudinary-fileupload" />
```
```js
// Get a Data URI from a canvas
var dataURI = canvas.toDataURL('image/png');

// Add it to the Blueimp/Cloudinary jQuery uploader to trigger upload
$('.cloudinary-fileupload').fileupload('add', { files: [ dataURI ] });

// Optionally listen for completion
$('.cloudinary-fileupload').on('cloudinarydone', function (e, data) {
  // handle the upload result in data.result
});
```
> **NOTE**: Base64 (Data URI) uploads have a 60 MB limit. For more information, see the [Upload via a Base64 Data URI](upload_parameters#upload_via_a_base_64_data_uri) section in the Upload parameters documentation.

## Upload multiple images

The file input field can be configured to support multiple file uploading simultaneously by setting the `multiple` HTML parameter. You should also manually bind an event handler to the `cloudinarydone` event to handle the results of multiple uploads. 

## Upload events

You can track the upload progress by binding an event handler to the following events: `cloudinarydone`, `fileuploadsend`, `cloudinaryprogress`, `cloudinaryalways` and `cloudinaryprogressall`.

### Building delivery URLs from the result

> **NOTE**: **Older browser fallback**: When the upload flow falls back to an iframe/redirect (for example, in Internet Explorer or other legacy browsers), the `cloudinarydone` event's `data.result` may not include `url` or `secure_url`. In that case, you can build the delivery URLs client-side from the returned identifiers.

```js
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
  var result = data.result;
  var baseOptions = {
    format: result.format,
    resource_type: result.resource_type,
    type: result.type,
    version: result.version
  };

  var url = $.cloudinary.url(result.public_id, $.extend({}, baseOptions, {
    secure: false
  }));

  var secureUrl = $.cloudinary.url(result.public_id, $.extend({}, baseOptions, {
    secure: true
  }));

  // Use url and secureUrl as needed
});
```

### Example handlers

Example 1: to bind an event handler to the `cloudinarydone` event and display a thumbnail preview of the uploaded image:

```js
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {  
    $('.preview').html(
       $.cloudinary.imageTag(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;});
```

Example 2: to update a progress bar according to the data of the `cloudinaryprogress` event:

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

### Abort an in-progress upload

If you want to let users cancel an upload that is already in progress, keep a reference to the `jqXHR` object returned from `data.submit()` and then call `jqXHR.abort()` (for example, from a Cancel button click handler).

```html
<input type="file" class="cloudinary-fileupload" />
<button id="cancel_button" type="button">Cancel upload</button>
```

```js
let jqXHR = null;

$('.cloudinary-fileupload').on('fileuploadadd', function (e, data) {
  // Start the upload and keep a handle to the in-flight request
  jqXHR = data.submit();
});

$('#cancel_button').on('click', function () {
  if (jqXHR) {
    jqXHR.abort();
    jqXHR = null;
  }
});
```

## Client side image validation before upload

Include the validation libraries and modify your script tags as follows (order is important):

```html
<script src="[folder-path]/jquery/dist/jquery.js" type="text/javascript"></script>
<script src="[folder-path]/jquery.ui/ui/widget.js" type="text/javascript"></script>
<script src="[folder-path]/blueimp-load-image/js/load-image.all.min.js"></script>
<script src="[folder-path]/blueimp-canvas-to-blob/js/canvas-to-blob.min.js"></script>
<script src="[folder-path]/blueimp-file-upload/js/jquery.iframe-transport.js" type="text/javascript"></script>
<script src="[folder-path]/blueimp-file-upload/js/jquery.fileupload.js" type="text/javascript"></script>
<script src="[folder-path]/blueimp-file-upload/js/jquery.fileupload-process.js"></script>
<script src="[folder-path]/blueimp-file-upload/js/jquery.fileupload-image.js" type="text/javascript"></script>
<script src="[folder-path]/blueimp-file-upload/js/jquery.fileupload-validate.js"></script>
<script src="[folder-path]/cloudinary-jquery-file-upload/cloudinary-jquery-file-upload.js" type="text/javascript"></script>
// [folder-path] is the mapping to the resources in your web application
```

The validation options are added when calling the `cloudinary_fileupload` method. For example:

```js
$(document).ready(function() {
  $('.cloudinary-fileupload').cloudinary_fileupload({
    disableImageResize: false,
    imageMaxWidth: 800,                   // 800 is an example value - no default
    imageMaxHeight: 600,                  // 600 is an example value - no default
    maxFileSize: 20000000,                // 20 MB is an example value - no default
    loadImageMaxFileSize: 20000000,       // default is 10 MB
    acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|ico)$/i
  });
});
```

> **See also**:
>
> * File Processing Options in the [Blueimp File Upload](https://github.com/blueimp/jQuery-File-Upload/wiki/Options#file-processing-options) wiki.
