File Uploader
Uploadcare File Uploader is an ultimate HTML5 File Uploader; it’s responsive and mobile-ready. The File Uploader is provided as a typical JavaScript library, has a tab-based UI, and provides an intuitive UX flow based on tabbed navigation.
Technically, File Uploader replaces your basic <input type="file">
controls
which then become buttons that activate the File Uploader dialog. Click the
button below and check out the File Uploader version 3.0 in action:
File Uploader Features
Implementing File Uploader helps you perform the following tasks:
- Uploading
- Add file uploading capabilities to your website or app.
- Upload files of any type and up to 5TB in size.
- Get files from various upload sources including local storage, camera, social media, and cloud storage services.
- Upload multiple files in one go.
- Track upload jobs with an individual progress bar for every file.
- Enable Drag’n’Drop for your upload user experience.
- Receive upload notifications.
- Implement a CDN for uploading files faster.
- Image Handling
- Show image previews.
- Implement custom image crop options.
- Edit, enhance, and filter images in any browser.
- Validation
- Validate files by their format or size.
- Control inbound image resolutions.
- Security
- Make your uploading system compatible with SOC2, HIPAA, and more.
- Reliability
- Make 99.9% percent of your uploads hit their target.
- All of your uploads go to the storage covered by SLA and 99.9% uptime.
Supported Browsers
We support modern browsers including Internet Explorer (10 and later), Edge, Firefox, Google Chrome, Safari, and Opera. It's recommended to update to the most recent verison. We provide support for at least two recent versions of each browser. More on the browser versions support.
The File Uploader will most probably run in older browser versions as well, except for Internet Explorer < 10.
If you need legacy browsers support including IE8, check out Uploadcare Widget v2.
Install
If you’re up to installing Uploadcare File Uploader manually, feel free to choose either option:
Please refer to integrations for ready-made solutions for some platforms.
Before proceeding with your install, check out the dependencies and existing types of File Uploader bundles.
Dependencies
Uploadcare File Uploader does not have any external dependencies except for jQuery. We provide two different File Uploader versions: with built-in jQuery and without it. See the types of existing File Uploader bundles for more info.
For instance, with the jQuery-enabled widget version you could go like:
var $ = uploadcare.jQuery;
$('body').append('It works!');
Bundles
There are a few types of js bundles:
uploadcare.full.js
— a full bundle with built-in jQuery,uploadcare.js
— a bundle without built-in jQuery,uploadcare.api.js
— a bundle without UI of the File Uploader and built-in jQuery, JavaScript API only,uploadcare.ie8.js
— a full bundle with built-in jQuery 1.x for IE 8 support (widget v. 2.x and below),uploadcare.lang.en.js
— a bundle without built-in jQuery,en
locale only.
Each bundle has its minified version. Just add .min
before .js
, e.g.
uploadcare.min.js
.
By default, uploadcare.min.js
is exported to NPM and other package managers.
Install from CDN
Embed the File Uploader client library using the <script>
element in the
<head>
section of each page where you’d like the File Uploader to show up.
This CDN link, for instance, embeds the File Uploader version with built-in jQuery:
<script src="https://ucarecdn.com/libs/widget/3.x/uploadcare.full.min.js" charset="utf-8"></script>
You might also happen to already use jQuery on your page. In this case, consider loading the light File Uploader version without built-in jQuery:
<script src="https://code.jquery.com/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="https://ucarecdn.com/libs/widget/3.x/uploadcare.min.js" charset="utf-8"></script>
Once you are done setting your public key and choosing an appropriate bundle,
look through your page <body>
and see where you want the File Uploader button to
appear. Place the following <input>
element there and make sure not to miss
the name
attribute:
<input type="hidden" role="uploadcare-uploader" name="my_file" />
Install from NPM
npm install uploadcare-widget
import uploadcare from 'uploadcare-widget'
Configure
Uploadcare File Uploader is highly customizable through File Uploader options. Most of the options can be set in one of the ways listed below. You can also implement mixed settings, i.e., when having multiple File Uploaders; their general behavior can be set using global variables while some of them may run based on local attributes.
You can set File Uploader options in the following ways:
- Interactively via the live config.
- Set File Uploader options globally, on page load.
- Set File Uploader options locally, when a new File Uploader instance is created.
- Via the
settings
object. - Mind how to set boolean options.
Note, the live config will also provide you with ready-made code snippets holding all the set options as local attributes.
Global variables
Globals are specified as global JavaScript variables in your <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 the File Uploader options can also be set within the settings
object.
See the JavaScript API reference for details. For
example:
uploadcare.openDialog(null, {
publicKey: 'demopublickey',
imagesOnly: true,
crop: '300x200'
});
Setting boolean options
All boolean
options are set globally with their 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
, the respective value should strictly be either "false"
or
"disabled"
.
Setting local options to true
:
<input data-option="data-option" />
<input data-option="true" />
<input data-option="" />
<input data-option />
Setting local options to false
:
<input data-option="false" />
<input data-option="disabled" />
Upload Sources
In many cases, local storage is not the best place to put your files. That is why Uploadcare implements over a dozen upload sources, so your users would not have to use their device storage if they aren’t keeping any files there.
Our file uploader, the Uploadcare File Uploader, uses the tabbed navigation to switch between upload sources. You can upload media from local and cloud storage, URLs, social media, and many more. The complete list follows.
In the File Uploader options, upload sources are controlled as separate tabs, and the
set of enabled tabs is controlled via the data-tabs
option.
The quickest way to play with the tab settings would be through
File Uploader configurator. You can also share live config
settings: the changes you implement will modify the configurator URL.
This reference, for instance, navigates you to the
File Uploader configured to use file
, camera
, and url
upload sources only.
Available sources
Configuring Upload Sources
You can configure the set of upload sources globally or per File Uploader instance.
The File Uploader option controlling the set of available sources
globally is called UPLOADCARE_TABS
; locally you can do it via the data-tabs
attribute.
In both cases, you provide a string holding space-separated list of tab names you want to enable in the File Uploader UI.
Configuring the set of sources globally:
<script>
UPLOADCARE_TABS = 'url file facebook';
</script>
Configuring the list of sources locally:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-tabs="url file facebook"
/>
Custom Tabs
We get you might extend the File Uploader with functions specific to your product. That’s done by adding custom tabs to the File Uploader.
You start with registering a tab under some name and adding it to the list of your File Uploader tabs. Let’s cover the process of adding a new tab, the one listing files uploaded via your File Uploader instance:
Registering a New Tab
You register a new tab via the registerTab
method.
<div id="uploader-placeholder">Uploading. Please wait...</div>
<script>
function favoriteFiles(container, button, dialogApi, settings) {
...
}
uploadcare.registerTab('favorites', favoriteFiles);
uploadcare.openPanel('#uploader-placeholder', null, {
tabs: 'favorites file facebook dropbox gdrive instagram vk',
favoriteFiles: [...]
});
</script>
Coding What the Tab Does
Once the tab is registered, we need to code its functionality. When making the
tab listing file uploads made via some File Uploader instance, next step is passing a
list of file UUIDs with the settings
object.
When a user selects a file for upload, its info can be passed to the dialog
using dialogApi
.
function favoriteFiles(container, button, dialogApi, settings) {
$.each(settings.favoriteFiles, function(i, uuid) {
container.append($('<img>', {
'class': 'favorite-files-image',
'src': settings.cdnBase + '/' + uuid + '/-/scale_crop/280x280/center/',
})
.on('click', function(e) {
dialogApi.addFiles([uploadcare.fileFrom('uploaded', uuid, settings)])
})
);
});
}
Adjusting the Tab Look
You can go beyond coding what the tab does to customizing ist look via CSS.
In case you want to add custom icons, make use of the <svg>
and <symbol>
elements. Check out the example below:
<svg width="0" height="0" style="position:absolute">
<symbol id="uploadcare--icon-favorites" viewBox="0 0 32 32">
<path d="M 16 22.928 L 23.416 27.4 L 21.454 18.965 L 28 13.292 L 19.37 12.552 L 16 4.6 L 12.629 12.552 L 4 13.292 L 10.546 18.965 L 8.584 27.4 Z"/>
</symbol>
</svg>
.uploadcare--menu__item_tab_favorites.uploadcare--menu__item_current {
color: #f0cb3c;
}
Live Example
Here’s a live example of the File Uploader with the custom tab listing files uploaded via the specific File Uploader instance:
Multiple Files
Uploadcare File Uploader allows you to handle multiple files in one go and track progress via individual progress bars.
The multi-uploading behavior is enabled by adding the boolean data-multiple
attribute set to true
to your File Uploader <input>
element, the one having its role specified as role="uploadcare-uploader"
.
<input type="hidden" role="uploadcare-uploader" name="my_files"
data-multiple="true"
/>
Here is the live File Uploader with multiple file uploads enabled:
Once many files are uploaded, they get stored as a
file group. You then get a group_id
instead of a file
UUID in the value.
Client-side image resize
It is common that you don’t want hi-res original images uploaded to your Uploadcare account. Doing so is inefficient on both ends:
- Sending large images over mobile networks can be expensive for your users.
- Large images take up your account storage limit and delivering those increase your traffic.
To handle the issue, Uploadcare File Uploader implements
client-side image optimization via the data-image-shrink
option.
The option is passed into your File Uploader as a string holding your preferred resolution and, optionally, a JPEG quality of the resulting image. The preferred resolution you provide does not affect original image aspect ratio.
Image Shrink outputs to:
- JPEG in case an input image has no transparency.
- PNG in case an input image includes transparent pixels.
Here are some examples of values you can specify for data-image-shrink
to
control the feature:
800x600
, shrinks images to 0.48 megapixels with the default JPEG quality of 80%.1600x1600 95%
, shrinks images to 2.5 megapixels with the JPEG quality set to 95%.
The resolution you set for optimized images should not exceed 5 megapixels. All EXIF info from your original images will be copied to the resized ones. The copied EXIF info includes image orientation, camera model, geolocation, and settings.
Input images will not be optimized in the following cases:
- When a client browser does not support all the required APIs.
- When images are uploaded from social media or URLs.
- If the
original resolution / target resolution
ratio falls behind2.0
. For example, you can not shrink a 2560x1560px (4 MP) image to 1600x1600px (2.5 MP) while this works with a 2448x3264px (8 MP) original. The reason we implemented this limit is to preserve an optimal balance between a decline in quality and drop in file size.
Live Examples
Resize to 1024x1024px on a client
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-preview-step=""
data-image-shrink="1024x1024"
/>
Resize multiple files to 640x640px on a client
<input type="hidden" role="uploadcare-uploader" name="my_files"
data-multiple=""
data-image-shrink="640x480"
/>
Localization
Uploadcare File Uploader is highly customizable and implements UI translations and custom pluralization rules. With ... locales, you can make your app instantly adapt to user languages.
There currently are: ar
az
ca
cs
da
de
el
en
es
et
fr
he
it
ja
ko
lv
nb
nl
pl
pt
ro
ru
sk
sr
sv
tr
uk
vi
zhTW
zh
You can either set an existing locale or add a custom one along with its pluralization rules.
Adding a locale
There is a chance the locale you need is not available in the File Uploader yet. In the case, it is worth contributing a new one. That is done by forking the main File Uploader repo and adding a new localization file to this list.
Another option is overriding specific locale items by altering your global File Uploader configuration:
UPLOADCARE_LOCALE = 'en';
UPLOADCARE_LOCALE_TRANSLATIONS = {
buttons: {
cancel: 'Cancel',
remove: 'Remove',
choose: {
files: {
one: 'Choose a file',
other: 'Pick files'
},
images: {
one: 'Choose an image',
other: 'Load images'
}
}
}
};
Compare the structure above with the default English locale and you will notice we used the snippet above to override two items in the default localization.
If a string item is missing in a locale you selected, and there is no override for it, English is a fallback. In fact, the English locale usually contains the most extensive set of items for latest File Uploader versions.
Pluralization rules
Pluralization rules deal with enumerabilty, it is when something can be counted.
File uploader locale items hold some quantitative values, and you might want to
override how those work.
In the English locale, for instance, you can find things like "1 file"
and
"3 files"
. Such behavior will require a special structure. You can find one of
those under the file:
key in the locale file.
Strings holding quantitative values are based on the output of a pluralization function. You pass an input number into a function, and it outputs a proper subkey related to your input.
function pluralize(number) {
// do something
return 'some_subkey';
}
There are two subkeys for the English localization: one
and other
. However,
it can get more complex with other languages. For example, take a look at
file:
subkeys for the Russian locale.
We use the %1
sequence to format numbers into pluralized strings.
Each locale we provide with the File Uploader is supplied with its Unicode-based
pluralization rules. If you wish to override those,
you can define a custom pluralization function and assign it to the
UPLOADCARE_LOCALE_PLURALIZE
variable.
The following setting makes the File Uploader use the message under the some
subkey
for input numbers 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';
};
Styling
Uploadcare File Uploader can be quickly integrated into your product. This is also the case with your user interface.
Scaling File Uploader Elements
The File Uploader is designed to organically inherit styles from your page: dialog elements get scaled in line with your font size. Check out the examples below:
Times New Roman, 12px:
Courier New, 18px:
Styling With CSS
The File Uploader is thoroughly annotated with CSS classes. It's your starting point into a deeper customization. You can find a class for every File Uploader item by inspecting its elements or sifting through the File Uploader source code.
The File Uploader dialog window look can be customized via the
uploadcare--dialog
class.
Changing Uploader Button Color
Changing the button color is one of the most common cases. It can be easily done with CSS:
See the Pen Changing uploader button color exampleby uploadcare (@uploadcare) on CodePen.
Button Shadow
You can add shadow and experiment with fonts and colors in CSS to any extent:
See the Pen Image dimensions validation exampleby uploadcare (@uploadcare) on CodePen.
Uploading Circle Color
You can display the file uploading progress. The fill color can be changed via
the CSS color
property, while border-color
will work for your background.
See the Pen Uploading circle color example #1by uploadcare (@uploadcare) on CodePen.
Here, you can test the File Uploader with a customized uploading circle:
See the Pen Uploading circle color example #2by uploadcare (@uploadcare) on CodePen.
Custom Progress Bar
You can replace the built-in progress bar. To do that, you need to listen to the
current File Uploader object and get it in the onChange
callback. It will
be a file object for regular File Uploaders or a group object for multiple File
Uploaders. After that listen to the progress
event and change your progress
bar in according to a current uploadProgress
.
The following installProgressBar
function does all that. It receives the two
arguments: File Uploader instance and progress bar DOM element. Everything else runs on
CSS, animation included.
See the Pen Custom progress bar exampleby uploadcare (@uploadcare) on CodePen.
Uploaded Image Preview
The default File Uploader behavior is when a user selects an image, and its preview is shown in the upload dialog. You might want to embed this preview in your page somewhere around the File Uploader button. Such a preview could be more informative than simply displaying file names and sizes.
See the Pen Image dimensions validation example #1by uploadcare (@uploadcare) on CodePen.
Note, you have full control over size and position of your embed, just use CSS.
Image preview for a multi-file File Uploader may look different:
See the Pen Image dimensions validation example #2by uploadcare (@uploadcare) on CodePen.
You can change the displayed images or rearrange the existing oness; all changes will then be reflected in the thumbnail list.
File Uploader Embed
We get that user experience matters and provide a good number of File Uploader customization options that cover both File Uploader appearance and behavior.
The look of the File Uploader can be changed via CSS, and the live config is a great starting point for controlling your File Uploader behavior.
Another thing you can do is embedding the File Uploader in your page by switching from the File Uploader dialog to panel.
Embed File Uploader Using Panel
The default behavior is when the File Uploader dialog appears on pushing a button. This covers the rest of your page with a semi-transparent background. It is a good fit when you use the File Uploader to fill in a single form field out of many.
However, when the purpose of your page is getting user-generated content, there
is a sense in showing the File Uploader on a page without any preceding clicks or taps.
The thing is called panel
.
<div id="uploader-placeholder">Uploading. Please wait...</div>
<script>uploadcare.openPanel('#uploader-placeholder');</script>
The snippet above replaces your DOM element with the uploadcare-placeholder
id and puts it in place once a user selects a file. This can be used to show
some indication of the uploading process, for instance. Also, unlike the dialog,
File Uploader panel can be closed by simply selecting a file.
Panel Styling
Same as the File Uploader dialog, panel can be customized.
Here is an example of customizing your File Uploader embed. Say, you don’t like its look because of the sharp border. The appearance of your embed can be changed via CSS. It goes like this:
#uploader-styling {
margin-top: 10px;
}
#uploader-styling .uploadcare--panel,
#uploader-styling .uploadcare--menu__item,
#uploader-styling .uploadcare--menu__items {
background-color: transparent;
border: 0;
}
#uploader-styling .uploadcare--panel {
flex-direction: column;
}
#uploader-styling .uploadcare--menu {
width: 100%;
height: 60px;
min-height: 60px;
}
#uploader-styling .uploadcare--menu__items {
padding-right: 0;
flex-direction: row;
}
Some dialog elements are rendered as iframes by Uploadcare servers, which does not let you customize CSS. However, we provide a set of specific methods to inject CSS into iframes.
Image crop
Cropping images is such a common task that we decided to implement it right in the File Uploader UI.
Uploadcare File Uploader features a good bunch of crop options including free crop.
Adding the feature to your File Uploader instance is done through implementing the
data-crop
option. Keep in mind this will alter your File Uploader
behavior and hence user experience: a new step gets added to the flow, that’s
where users will be able to apply cropping.
This alters the usual File Uploader behavior. Now, after users select their images for uploading, they encounter a step where cropping can be applied.
How Cropping Works
Technically, image cropping works as post-processing via the Image Processing feature:
- Original images go to an Uploadcare project associated with a Public Key set for your File Uploader instance.
- Crop is applied as the
crop
image processing operation by injecting its URL directive into original URLs. - The File Uploader returns resulting CDN URLs with injected
crop
.
Configuring Crop
Crop options are put into the data-crop
attribute as a string holding
comma-separated crop presets. When you define several presets, users will be
able to choose from the related crop options right in the UI.
Each crop preset is a combination of a size or ratio definition and an optional keyword:
"disabled"
, crop is disabled. Can’t be combined with other presets.""
or"free"
, crop is enabled; users can freely select any crop area on their images."2:3"
, any area with the aspect ratio of 2:3 can be selected for cropping."300x200"
— same as above, but if the selected area is greater than 300x200 pixels, the resulting image will be downscaled to fit the dimensions."300x200 upscale"
— same as above, but even if the selected area is smaller, the resulting image gets upscaled to fit the dimensions."300x200 minimum"
— users won’t be able to define an area smaller than 300x200 pixels. If an image we apply crop to is smaller than 300x200 pixels, it will be upscaled to fit the dimensions.
Crop examples
Free crop:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-crop=""
/>
Choosing from predefined aspect ratios:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-crop="free, 16:9, 4:3, 5:4, 1:1"
/>
Fixed aspect ratio:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-crop="4:3"
/>
Fixed size with upscaling:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-crop="400x300 upscale"
/>
Default files in Uploader dialog
Uploadcare File Uploader allows you to make specified files appear in the File Uploader dialog on open.
Specifying files that appear on File Uploader dialog open is implemented by adding the
value
attribute to your File Uploader <input>
element. The attribute may either be
empty or hold a file CDN URL or UUID.
If you set the value
externally and trigger the DOM change event, it affects
the File Uploader. For instance, setting it to a file UUID or a CDN URL will result in
that file loaded into the File Uploader. You can do this for a live File Uploader or even
before it loads.
Here’s how you do it:
<input type="hidden" role="uploadcare-uploader" name="my_file"
data-public-key="232d896709883f79bfaf"
value="https://ucarecdn.com/9dd2f080-cc52-442d-aa06-1d9eec7f40d1/"
/>
<!--
Also valid:
value="9dd2f080-cc52-442d-aa06-1d9eec7f40d1"
-->
You may also want to check out a live example:
JS snippets and CSS tricks
In this cookbook part, you can find popular code examples and resolutions of common tasks when working with File Uploader. Less words, more code!
Paste an image from the clipboard
const widget = uploadcare.Widget("[role=uploadcare-uploader]");
widget.onDialogOpen((dialog) => {
function uploadFromClipboard(e) {
let data = e.clipboardData;
if (!!data && !!data.items.length) {
// check if clipboard data is image
if (data.items[0].type.indexOf("image") != 0) {
alert("No image in the clipboard");
return;
}
let blob = e.clipboardData.items[0].getAsFile();
dialog.addFiles("object", [blob]);
}
}
window.addEventListener("paste", uploadFromClipboard);
});
Get a CDN URL of an uploaded file
For a single-upload widget.
// get a widget reference
const widget = uploadcare.SingleWidget("[role=uploadcare-uploader]");
// listen to the "upload completed" event
widget.onUploadComplete(fileInfo => {
// get a CDN URL from the file info
console.log(fileInfo.cdnUrl);
});
Get CDN URLs of uploaded files
For a multi-upload widget.
// get a widget reference
const widget = uploadcare.MultipleWidget("[role=uploadcare-uploader]");
// listen to the "change" event
widget.onChange(function (group) {
// get a list of file instances
group.files().forEach(file => {
// once each file is uploaded, get its CDN URL from the fileInfo object
file.done(fileInfo => {
console.log(fileInfo.cdnUrl);
});
});
});
Get a group CDN URL
For a multi-upload widget.
// get a widget reference
const widget = uploadcare.MultipleWidget("[role=uploadcare-uploader]");
// listen to the "upload completed" event
widget.onUploadComplete(groupInfo => {
// get CDN URL from group information
console.log(groupInfo.cdnUrl);
});
Get a CDN URL of an uploaded file/group
For a dialog window.
// create a new dialog object
const dialog = uploadcare.openDialog(null, '', {
multiple: false // set to true for multi-file uploads
});
// get a file or group instance
dialog.done(res => {
// once a file or group is uploaded, get its CDN URL
res.promise().done(info => {
console.log(info.cdnUrl);
});
});
Get a camera-recorded video duration
// get widget reference
const widget = uploadcare.Widget("[role=uploadcare-uploader]");
let cameraRecDuration = null;
let recStart = null;
let recEnd = null;
// calculate webcam recording duration
document.body.addEventListener("click", e => {
// user clicks "start recording"
if (e.target.classList.contains("uploadcare--camera__button_type_start-record")) {
recStart = new Date().getTime();
}
// user clicks "stop recording"
if (e.target.classList.contains("uploadcare--camera__button_type_stop-record")) {
recEnd = new Date().getTime();
cameraRecDuration = (recEnd - recStart) / 1000;
console.log("Duration: ", cameraRecDuration);
}
});
Check if a file was added or removed
// get widget reference
const widget = uploadcare.Widget("[role=uploadcare-uploader]")
// get dialog object to access its API
widget.onDialogOpen(dialog => {
// listen to "file added" event
dialog.fileColl.onAdd.add(file => {
console.log("File added", file)
});
// listen to "file removed" event
dialog.fileColl.onRemove.add(file => {
console.log("File removed", file)
});
});
Get the upload source
// get widget reference
const widget = uploadcare.Widget("[role=uploadcare-uploader]");
// listen to the "upload completed" event
widget.onUploadComplete(fileInfo => {
// get source details from file information
console.log(fileInfo.sourceInfo.source);
});
Add an overlay to the crop
.uploadcare--jcrop-tracker::after{
content: "";
position: absolute;
width: 100%;
height: 100%;
left: 0;
/* URL of the overlay image */
background-image: url(<https://i.imgur.com/hSbF6v0.png>);
background-size: cover;
background-position: center;
}
.uploadcare--jcrop-tracker:first-of-type{
opacity: 1 !important;
background-color: transparent !important;
}
Get a selected crop preset
<input type="hidden" role="uploadcare-uploader" name="my_file" id="uploadcare-file" data-crop="2:3, 5:6, 16:9" />
let currentPreset = '2:3';
document.addEventListener('click', e => {
// user clicks on a crop preset icon
if (e.target.classList.contains('uploadcare--crop-sizes__item') || e.target.classList.contains('uploadcare--crop-sizes__icon')) {
// get the caption of the preset selected
currentPreset = document.querySelector('.uploadcare--crop-sizes__item_current').dataset.caption;
console.log(currentPreset);
}
});
Upload an image from Base64
// original base64 image
const b64data = "data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
// convert dataURI to a File object
function dataURLtoFile(dataurl, filename) {
let arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type:mime});
}
// convert a base64 image to a File object
const fileToUpload = dataURLtoFile(b64data, "image");
// upload the file to Uploadcare
let upload = uploadcare.fileFrom("object", fileToUpload);
upload.done(fileInfo => {
console.log("File uploaded: ", fileInfo.cdnUrl);
});
Render the uploaded image preview
// get widget reference
const widget = uploadcare.Widget("[role=uploadcare-uploader]");
widget.onUploadComplete(fileInfo => {
const preview = document.createElement("img");
// create a preview of the uploaded image of 200px width
preview.src = fileInfo.cdnUrl + "-/resize/200x/";
// add the thumbnail to the page
document.body.appendChild(preview);
});
Add custom names to crop presets
<input type="hidden" role="uploadcare-uploader" name="my_file" id="uploadcare-file" data-crop="free,1:1,2:3" />
.uploadcare--crop-sizes__item {
overflow: visible;
}
.uploadcare--crop-sizes__item:nth-child(1)::after {
content: "Free form";
}
.uploadcare--crop-sizes__item:nth-child(2)::after {
content: "Square";
}
.uploadcare--crop-sizes__item:nth-child(3)::after {
content: "Portrait";
}
Add custom widget button labels
<input type="hidden" role="uploadcare-uploader" id="uploadcare-file-1" data-btn-text="I'm the first buton" />
<input type="hidden" role="uploadcare-uploader" id="uploadcare-file-2" data-btn-text="I'm the second one" />
<input type="hidden" role="uploadcare-uploader" id="uploadcare-file-3" data-btn-text="And I am the third" />
// get an array of widget references
const widgets = uploadcare.initialize();
// update each widget button text with the data-btn-text attribute's value
widgets.forEach(widget => {
widget.inputElement.nextSibling.querySelector(".uploadcare--widget__button_type_open").innerHTML = widget.inputElement.getAttribute("data-btn-text");
});
Reset widget after upload
// get widget reference
const widget = uploadcare.Widget("[role=uploadcare-uploader]");
// once a file is uploaded, output its URL and reset the widget
widget.onUploadComplete(fileInfo => {
console.log(fileInfo.cdnUrl);
widget.value(null);
});
Add a custom message to the dialog
/* turn the "after" pseudo element of the dialog container's div into a hint */
.uploadcare--tab__content::after {
content: "Wake up Neo... The Matrix has you... Follow the white rabbit🐇";
padding: 1em;
margin: 2em;
background-color: #000;
color: #00ff00;
border-radius: 5px;
}