Widget documentation

Uploadcare comes with the widget that replaces your general <input type="file"> controls. Here’s the latest version in action:

  • This documentation is for the version 3.1.1 of the widget. If you're looking for the widget v2 docs, check here.
  • Migration guide from v2 to v3 here.

Installation

You’re free to choose from the install methods listed below.

CDN

Embed our client library via <script> tag in the <head> section of each page where you’d like to make use of Uploadcare Widget. Just use this CDN link to use the widget version with built-in jQuery,

<script src="https://ucarecdn.com/libs/widget/3.1.1/uploadcare.full.min.js" charset="utf-8"></script>

Or, if you’re already using jQuery on your page, consider loading the light version of our widget without built-in jQuery,

<script src="https://code.jquery.com/jquery-3.2.1.min.js" charset="utf-8"></script>
<script src="https://ucarecdn.com/libs/widget/3.1.1/uploadcare.min.js" charset="utf-8"></script>

Other install methods

NPM

npm install uploadcare-widget

ES6

import uploadcare from 'uploadcare-widget';

CommonJS

var uploadcare = require('uploadcare-widget');

Bower

bower install uploadcare

Usage

Once you’re done with the install, there are two simple steps to take to actually use the widget.

Set your public key. This can also sit in the <head> section,

<script>
  UPLOADCARE_PUBLIC_KEY = 'demopublickey';
</script>

Your secret key is not required for the widget (it’s quite careless for your page to include any secret keys anyway.)

Insert widget element into your form,

<input type="hidden" role="uploadcare-uploader" name="my_file" />

By default, the library looks for inputs with the specified role attribute and places widgets there. Once a file is uploaded, this <input> gets a CDN link with a file UUID. Your server then receives this link instead of file content.

We suggest placing the widget somewhere at the top of your form. Unlike regular inputs, our widget starts uploading files immediately after they get selected by a user, not on form submission. That way users can fill out the rest of your form while an upload is in progress. This can be a real time saver.

Configuration

Uploadcare Widget is highly customizable through widget options. Check out the configuration page to see some of them in action.

There are two ways to set widget options:

  • Global options are set when your page loads.
  • Local — when a new widget is created.

Changing any options during widget operation won’t affect its behavior.

Global variables

Globals are specified as global JavaScript variables in a <script> tag, for example,

<script>
  UPLOADCARE_PUBLIC_KEY = 'demopublickey';
  UPLOADCARE_LOCALE = 'ru';
</script>

Local attributes

Local options are specified in the target <input> tag as data-* attributes, for example,

<input type="hidden" role="uploadcare-uploader"
  data-public-key="demopublickey"
  data-images-only
/>

Settings object

Most of widget options can also be set within the settings object, see JavaScript API docs for more info.

uploadcare.openDialog(null, {
  publicKey: 'demopublickey',
  imagesOnly: true,
  crop: '300x200'
});

Here is a summary of all available options:

Public key string

Global: UPLOADCARE_PUBLIC_KEY
Local: data-public-key
Object key: publicKey

Your public key.

Multiple boolean

Global: N/A
Local: data-multiple
Object key: multiple

If true, the widget allows selecting and uploading multiple files. Turned off by default.

Multiple max integer

Global: N/A
Local: data-multiple-max
Object key: multipleMax

A maximum number of files allowed for a single upload. The default value is 0 which stands for no limit.

Multiple min integer

Global: N/A
Local: data-multiple-min
Object key: multipleMin

A minimum number of files allowed per upload. The default value is 1. Note that setting the value to 0 bears no meaning since a file group should contain at least one file.

Images only boolean

Global: UPLOADCARE_IMAGES_ONLY
Local: data-images-only
Object key: imagesOnly

If true, only image files can be uploaded. Turned off by default.

Preview step boolean

Global: UPLOADCARE_PREVIEW_STEP
Local: data-preview-step
Object key: previewStep

If true, a preview step will follow once files are selected (otherwise, a file dialog closes.) Turned off by default.

Crop string

Global: UPLOADCARE_CROP
Local: data-crop
Object key: crop

Manual crop options, see below. If an uploaded file is an image, user will be able to select crop area. This option does not force images only, though.

Works together with the multiple option starting from version 2.3.0.

Image shrink string

Global: UPLOADCARE_IMAGE_SHRINK
Local: data-image-shrink
Object key: imageShrink

Allows to reduce image size before uploading to save traffic and storage space. See the detailed syntax below. This option does not force images only.

Clearable boolean

Global: UPLOADCARE_CLEARABLE
Local: data-clearable
Object key: N/A

Allows user to remove uploaded files from the widget. Please note that those files are not deleted from your account.

Tabs string

Global: UPLOADCARE_TABS
Local: data-tabs
Object key: tabs

Space-separated ordered list of upload sources (e.g. local files, URLs or Facebook), see below.

Input accept types string

Global: UPLOADCARE_INPUT_ACCEPT_TYPES
Local: data-input-accept-types
Object key: inputAcceptTypes

Sets the accept attribute for a file picking dialog. By default, the value is image/* if images only is true or empty if not. null value means accept always should be empty regardless of images only. You can find other values in this specification. Please note that this is not a replacement for file validation because users can still choose any type of file by drag&drop or from URL.

Preferred types string

Global: UPLOADCARE_PREFERRED_TYPES
Local: data-preferred-types
Object key: preferredTypes

Defines the list of preferred MIME types. The list should be ordered and contain space-separated MIME types. Common parts can be marked with asterisks: image/* application/vnd.openxmlformats-officedocument.*. If no MIME types match the criteria or preferred types aren’t set, default formats are used.

Keep in mind that some cloud services can export data in different formats. For example, Google document can be exported as Word document, PDF or plain text.

System dialog boolean

Global: UPLOADCARE_SYSTEM_DIALOG
Local: data-system-dialog
Object key: N/A

Forces native file picking dialog over the Uploadcare one. Thus, making widget behavior as close as possible to the usual <input type="file">. Native behavior is achieved at the expense of support for social networks and cloud services, image crop, and preview. Multiple file selection would still work, though. The option doesn’t work in old browsers versions, instead the dialog falls back to the Uploadcare one.

Locale string

Global: UPLOADCARE_LOCALE
Local: N/A
Object key: N/A

The widget supports a good number of languages.

Currently there are:

English locale is used by default.

Locale translations object

Global: UPLOADCARE_LOCALE_TRANSLATIONS
Local: N/A
Object key: N/A

Custom localization options, see below.

Locale pluralize object

Global: UPLOADCARE_LOCALE_PLURALIZE
Local: N/A
Object key: N/A

Custom pluralization options, see below.

Secure signature string

Global: UPLOADCARE_SECURE_SIGNATURE
Local: data-secure-signature
Object key: secureSignature

In case you enable signed uploads for your project, you’d need to provide the widget with signature and expire. Read more about signed uploads in our docs covering uploads.

The signature is a MD5 hex-encoded hash from a concatenation of secret_key and expire.

Works together with the secure expire option.

Secure expire integer

Global: UPLOADCARE_SECURE_EXPIRE
Local: data-secure-expire
Object key: secureExpire

Stands for the Unix time to which the signature is valid, e.g. 1454902434.

Works together with the secure expire option.

Live boolean

Global: UPLOADCARE_LIVE
Local: N/A
Object key: N/A

If true, inputs are initialized automatically, see below. Enabled by default.

Manual start boolean

Global: UPLOADCARE_MANUAL_START
Local: N/A
Object key: N/A

If true, initialization of inputs is invoked manually, see below. Disabled by default.

CDN base url

Global: UPLOADCARE_CDN_BASE
Local: data-cdn-base
Object key: cdnBase

Defines schema and CDN domain. Can be changed to one of the predefined values or your custom CNAME. Defaults to https://ucarecdn.com/.

Do not store boolean

Global: UPLOADCARE_DO_NOT_STORE
Local: data-do-not-store
Object key: doNotStore

Forces files uploaded with a widget not to be stored. For instance, you might want to turn this on when autostore is enabled in your project, but you aren’t willing to store files uploaded with a particular widget.

Validators array

Global: N/A
Local: N/A
Object key: validators

JavaScript-only option. Defines an array of validation functions. See validators documentation.

Boolean options

All boolean options are set globally with general JavaScript boolean values.

UPLOADCARE_CLEARABLE = true;
UPLOADCARE_PREVIEW_STEP = false;

When setting boolean options locally in HTML tag attributes, any value is interpreted as true, even an empty one. However, when setting local options to false, an attribute value should strictly be either "false" or "disabled".

Setting a local option to true,

<input data-option="data-option" />
<input data-option="true" />
<input data-option="" />
<input data-option />

Setting a local option to false,

<input data-option="false" />
<input data-option="disabled" />

Tabs (Upload Sources)

The widget can upload files from local storages, URLs, social media, and many other sources. Each upload source has its own tab in the widget dialog.

A complete list of tabs supported in the latest widget version (3.1.1) is provided below.

CodeFile SourceDefault
fileLocal diskOn
cameraLocal webcamOn
urlAny URLOn
facebookFacebookOn
gdriveGoogle DriveOn
gphotosGoogle PhotosOn
dropboxDropboxOn
instagramInstagramOn
evernoteEvernoteOn
flickrFlickrOn
skydriveOneDriveOn
boxBoxOff
vkVKOff
huddleHuddleOff

The set can be reconfigured by specifying the tabs you need as space-separated values.

Globally,

<script>
  UPLOADCARE_TABS = 'url file facebook';
</script>

or locally,

<input type="hidden" role="uploadcare-uploader"
  data-tabs="url file facebook"
/>

Input Value

The value of the [role=uploadcare-uploader] input may either be empty or contain a CDN link with file UUID.

If you set the input value externally and trigger the DOM change event, it will be reflected in the widget. For example, setting it to a file UUID or a CDN link will show that file in the widget as an uploaded one. You can do this for a live widget or even before it loads.

Here’s an example of a predefined value,

<input type="hidden" role="uploadcare-uploader"
  data-public-key="1c86ca998ba22e75fbc6"
  value="https://ucarecdn.com/9dd2f080-cc52-442d-aa06-1d9eec7f40d1/"
/>

<!--
  Also valid:
  value="9dd2f080-cc52-442d-aa06-1d9eec7f40d1"
-->

Styling

Our widget is designed to inherit styles from your page and to be highly customizable at the same time. All elements are scaled in line with font size.

Times New Roman, 12px:

Courier New, 18px:

Uploadcare Widget is thoroughly annotated with CSS classes which can be styled on top of the defaults. You can find the class for every item by inspecting widget elements or sifting through the original source.

You can also customize the look of upload dialog with corresponding uploadcare--dialog class.

More examples can be found in our cookbook and customization tutorial.

Custom Localization

It’s possible that your locale is not available in the widget yet. If that’s the case, contributing your locale might be a good idea. This can be done by forking the main repository and adding a localization file here.

However, if you’d like to override text in specific parts of the widget, you can configure it globally,

UPLOADCARE_LOCALE = 'en';
UPLOADCARE_LOCALE_TRANSLATIONS = {
  buttons: {
    cancel: 'Cancel',
    remove: 'Remove',
    choose: {
      files: {
        one: 'Choose a file',
        other: 'Choose files'
      },
      images: {
        one: 'Choose an image',
        other: 'Choose images'
      }
    }
  }
};

Compare the structure above with default English localization. You should notice this overrides two strings in the original localization.

If a string is both missing in the selected localization and is not overridden, English is used as a fallback. In fact, English is always the most extensive localization for latest widget version.

Pluralization

You might also want to override quantitative strings. For example, "1 file" and "3 files". This would require a special structure as seen under the file: key in English localization.

Strings that are altered in line with a number of input features are based on the output of a pluralization function. The function, given an input number, returns the name of a subkey to use.

function pluralize(number) {
  // do something
  return 'some_subkey';
}

There are two of such subkeys for English localization: one and other. However, it might be more difficult in languages with more complex pluralization rules. For example, take a look at file: subkeys for Russian locale.

You might’ve noticed, to format a number into pluralized strings, a %1 sequence is used.

Each locale we provide with the widget is supplied with its pluralization rules. But, if you wish to override those, you can write a custom function and assign it to the UPLOADCARE_LOCALE_PLURALIZE variable.

For example, the following configuration makes the widget to use the message under the some subkey for numbers of files from 2 to 10.

UPLOADCARE_LOCALE_TRANSLATIONS = {
  file: {
    one: 'Only one file! :(',
    some: 'Only %1 files. Upload more.',
    many: '%1 files!! That\'s a lot.'
  }
};
UPLOADCARE_LOCALE_PLURALIZE = function(n) {
  if (n === 1) return 'one';
  if (n > 1 && n <= 10) return 'some';
  return 'many';
};

Requirements

The widget doesn’t have any external dependencies except for jQuery. We provide two versions of the widget: with built-in jQuery and without it (see usage). For instance, when using the version with jQuery you could do that,

var $ = uploadcare.jQuery;
$('body').append('It works!');

Our widget should work perfectly in a couple of the latest versions of major desktop browsers: Internet Explorer, Edge, Firefox, Google Chrome, Safari, and Opera. It is most likely to run well in older versions of major browser too, except for Internet Explorer < 10.

If you need to support of old browsers and IE8 too, you might use v2 of widget.

Automatic File Storing

When the autostore feature is enabled in project settings, uploaded files are stored on our storage automatically. There’s no need to additionally store them. This might prove handy when your app retains most (or all) of the uploaded files.

If autostore is disabled, you’d need to make a separate server-side API call in order to store your files. This should be done after a form listing out uploaded files is submitted. Files that weren’t through a store operation are deleted within a 24-hour time span.

If autostore is enabled in your project settings, but you don’t want to store files uploaded with a particular widget, check out this option.

Initialization

By default, every new [role=uploadcare-uploader] element appearing on a page (at any time) gets initialized as a widget in about ~100 ms. A single JavaScript timer provides this behavior. It shouldn’t have any impact on performance in typical applications. However, if every cycle counts and you feel this is weighty, consider disabling the UPLOADCARE_LIVE option.

This way, you’d have to deal with manually adding widget inputs after a page loads.

Though, all the widgets on a page would still be initialized during its load. You might not want it, especially if you plan introducing some preparations prior to instantiating widgets. Consider using UPLOADCARE_MANUAL_START together with uploadcare.start() in the case. A settings object should be passed into uploadcare.start() to override global settings. You can pass any global settings, but keep in mind that keys are camelCased, not CAPITALIZED_WITH_UNDERSCORES.

UPLOADCARE_MANUAL_START = true;

jQuery(function($) {
  var $.getJSON('/uploadcare.json', function(data) {
    uploadcare.start({
      publicKey: data.publicKey, // overrides UPLOADCARE_PUBLIC_KEY
      crop: data.crop // overrides UPLOADCARE_CROP
    });
  });
});

Manual Crop

Uploadcare Widget features custom crop. Enabling it will alter the usual widget behavior. Now, after a user selects an image to upload, a cropping step arises where that image can be cropped according to your settings. Your project will still be supplied with the original image itself, while cropping will be put into a resulting CDN URL as the on-the-fly CDN API operation.

Crop options are put into a string holding one or more comma-separated crop presets. When several presets are defined, users will be able to pick any of them during the crop step.

Each preset consists of a size definition and an optional keyword.

  • "disabled" — crop is disabled. Can’t be combined with other presets;
  • "" or "free" — crop is enabled and users will be able to freely select any area on an image;
  • "2:3" — users will be able to select an area with the aspect ratio of 2:3;
  • "300x200" — same as above, but if the selected area is greater than 300x200, it will be downscaled to fit the dimensions;
  • "300x200 upscale" — same as above, but the area will be scaled even if it is smaller than the specified dimensions;
  • "300x200 minimum" — users won’t be able to select an area smaller than 300x200. In case an image itself is smaller than 300x200, it will be upscaled.

Crop examples

Crop with no restrictions,

<input type="hidden" role="uploadcare-uploader" data-images-only
  data-crop=""
/>

Five presets with different aspect ratios, one of which is free crop,

<input type="hidden" role="uploadcare-uploader" data-images-only
  data-crop="free, 16:9, 4:3, 5:4, 1:1"
/>

Crop with fixed aspect ratio,

<input type="hidden" role="uploadcare-uploader" data-images-only
  data-crop="4:3"
/>

Fixed-size crop with upscaling,

<input type="hidden" role="uploadcare-uploader" data-images-only
  data-crop="400x300 upscale"
/>

Shrink Images Before Uploading

Sometimes you don’t want to have hi-res original images uploaded to your account. At once, sending larger images can be expensive or too slow for your users as well. For instance, this is the case when sending 10+ megapixel images from your smartphone over a cellular network.

Image shrink option is provided as a string holding the preferred resolution and, optionally, a JPEG quality of the resulting image (note, the original aspect ratio of an input image is preserved despite the set resolution.)

  • 800x600 — shrink an image to 0.48 megapixels with the default JPEG quality (80%.)
  • 1600x1600 95% — shrink an image to 2.5 megapixels with 95% JPEG quality.

The resolution you set should not exceed 5 megapixels. All EXIF info from original images (including orientation, camera model, geolocation, and settings) will be copied to resized images.

Images won’t be shrunk in the following cases:

  • if a browser does not support all the required APIs.
  • if an image is uploaded from social sources or URL.
  • if an image is less than two times larger than the preferred size. For example, an image with the resolution of 2560x1560px (4 MP) won’t be shrunk to 1600x1600px (2.5 MP), but a 2448x3264px (8 MP) one will. The reason is in the first case the decline in quality will be significant, while the drop in file size will stay relatively low.

Shrink examples

Shrink to 1024x1024 pixels,

<input type="hidden" role="uploadcare-uploader"	data-preview-step=""
  data-image-shrink="1024x1024"
/>

The widget, capable of shrinking multiple files to the resolution of 640x480 pixels (0.3 MP.),

<input type="hidden" role="uploadcare-uploader"
  data-multiple=""
  data-image-shrink="640x480"
/>

Mobile Layout

Starting from the version 1.0.0, our web widget can be properly used on mobile devices. On small screens, the uploading dialog gets opened full-screen, and layout is changed for the sake of better user experience. This feature is turned on automatically on pages with the proper <meta name="viewport"> tag. Viewport tag reports which screen size was expected when you created a page. It is required for all responsive websites. If your site does not support responsive issues, but you still want to provide mobile devices with the appropriate Uploadcare Widget, you can include this relatively safe viewport tag to your page,

<meta name="viewport" content="width=device-width, initial-scale=1" />

This tag will trigger a mobile browser to show your page with 1:1 initial zoom, but will still allow users to adjust the zoom manually.

Questions?

We're always happy to help with code or other questions you might have! Search our site for more information or send us an email!