Adding Custom Data During Uploading Jqueryfile Upload
File Uploader
Uploadcare File Uploader is a responsive and mobile-ready HTML5 website solution that allows users to select and upload multiple files from various sources. Also, it includes an in-browser image editor. Yous can customize the appearance and functionality to match your website and task.
File Uploader is supplied as a JavaScript library. Information technology overrides an <input type="file">
control on an HTML page with a button that opens upward the File Uploader dialog. Like this:
File Uploader Features
File Uploader helps you perform the following tasks:
- Uploading
- Add a file uploading adequacy to your website or app.
- Upload files of whatever type and upwards to 5 TB in size.
- Become files from various upload sources, including local storage, camera, social media, and cloud storage services.
- Upload multiple files in one get.
- Rails upload jobs with an individual progress bar for each file.
- Speed up the uploading with the uploading network (it works like CDN).
- Image Handling
- Prove prototype previews.
- Implement custom prototype crop options.
- Edit, enhance, and use photograph filters to images in whatsoever browser.
- Validation
- Validate files past their format or size.
- Automatically resize large incoming images.
- Security
- Make your uploading system uniform with SOC2, HIPAA, and more.
- Forestall remote code execution through File Uploading.
- Forestall code execution in uploaded files like
SVG
,html
andxml
.
- Reliability
- All of your uploads get to the storage covered by SLA and with a 99.9% uptime.
Supported browsers
The electric current File Uploader (v3) works in all modernistic browsers, desktop and mobile. Here's a listing of supported browsers:
Desktop | Mobile |
---|---|
Chrome: 37+ | Android Browser: 4.4+ |
Firefox: 32+ | Opera Mobile: 8+ |
Safari: 9+ | iOS Safari: ix+ |
Edge: 12+ | IE Mobile: 11+ |
IE: ten+ | Opera Mini: Last |
The File Uploader will most probably run in older browser versions also. In example you need legacy browser back up (IE8), endeavor out File Uploader v2.
More on browser version back up.
Installation
Select either option to install File Uploader:
- Global installation
- NPM
Refer to no-code integrations to employ File Uploader with your website platform like Shopify, etc.
Before proceeding with your install, bank check out the dependencies and File Uploader bundles below.
Dependencies
Uploadcare File Uploader doesn't have whatever external dependencies except for jQuery. More often than not, File Uploader comes in two versions: with and without jQuery.
For instance, you tin use jQuery commands on the page if yous included a bundle with jQuery:
var $ = uploadcare.jQuery; $ ( 'body' ) . suspend ( 'It works!' ) ;
javascript
Bundles
Depending on your project, you tin select a specific File Uploader JS library parcel:
-
uploadcare.full.js
— a full bundle with built-in jQuery -
uploadcare.js
— a default bundle without jQuery -
uploadcare.api.js
— a bundle without File Uploader UI and jQuery JavaScript API simply -
uploadcare.ie8.js
— a full bundle with built-in jQuery 1.x for IE viii support (widget five.ii.x and earlier) -
uploadcare.lang.en.js
— a parcel without jQuery,en
locale only
Include a minified bundle version by adding .min
before .js
.
Past default, minified (and without jQuery) uploadcare.min.js
is exported to NPM and other packet managers.
Global installation
Become your Public Key in the Dashboard and include this into the <caput>
:
Note: If you already utilize jQuery, you can utilize the alternative package that comes without jQuery, so y'all won't download information technology twice.
At present you lot can use the Uploader:
<input blazon = "hidden" role = "uploadcare-uploader" name = "my_file_input" />
html
NPM
npm install uploadcare-widget
bash
import uploadcare from 'uploadcare-widget'
javascript
You can become a file uploader instance and configure it with configuration object:
<input id = "uploader" blazon = "hidden" />
html
const widget = uploadcare. Widget ( "#uploader" , { publicKey: 'demopublickey' } ) ;
javascript
Configure
Set of features, such as upload sources, prototype editing tools, can be customized via File Uploader options. You lot can have mixed settings for different File Uploader instances. Global variables will touch all File Uploader instances, and local attributes will override global settings.
Hither's how you lot can configure File Uploader:
- Dashboard with a web UI. It generates lawmaking that you lot can use on your page or share a link to a colleague with your config.
- Global variables, initialized on page load.
- Local attributes, initialized when a new File Uploader instance is created.
- The
settings
object.
Global variables
Globals are specified as global JavaScript variables in your <script>
tag. For example:
<script > UPLOADCARE_PUBLIC_KEY = 'demopublickey' ; UPLOADCARE_LOCALE = 'ru' ; UPLOADCARE_CLEARABLE = true ; </script >
html
Local attributes
Local options are specified in the target <input>
tag as data-*
attributes. For example:
<input type = "hidden" role = "uploadcare-uploader" information-public-primal = "demopublickey" information-images-but />
html
When setting boolean options locally in HTML tag attributes, any value or no value is considered every bit truthful
:
<input data-choice = "true" /> <input data-choice = "any-value" /> <input data-option = " " /> <input data-option />
html
To disable a local pick, use either:
<input data-option = "false" /> <input information-option = "disabled" />
html
Settings object
Most of the File Uploader options tin can also be set up within the settings
object. Encounter the JavaScript API reference for more details. For example:
<input id = "uploader" type = "subconscious" />
html
const widget = uploadcare. Widget ( "#uploader" , { publicKey: 'demopublickey' , imagesOnly: true , crop: '300x200' } ) ;
javascript
Upload Sources
File Uploader supports xiv upload sources, including local file storage, web photographic camera; external URL; cloud services, and social networks. In UI, the sources are shown every bit tabs.
- Supported Upload Sources
- Dashboard
- Manual Configuration
The set of enabled upload sources is controlled via the data-tabs
pick.
Start with Dashboard and select the sources y'all'd similar to go out. Copy the generated code snippet.
List of supported Upload Sources
Configuring Upload Sources
You tin configure the set up of upload sources globally or per File Uploader instance. The global parameter is chosen UPLOADCARE_TABS
. Locally you can use the information-tabs
aspect.
In both cases, you'll pass a infinite-separated string with tab names.
Configuring the set of sources globally:
<script > UPLOADCARE_TABS = 'url file facebook' ; </script >
html
Configuring the list of sources locally:
<input type = "subconscious" function = "uploadcare-uploader" proper noun = "my_file" data-tabs = "url file facebook" />
html
Custom tabs
You can add custom tabs into your File Uploader. These tabs tin be additional upload sources or any you design them to exist. For instance, brandish all uploaded files.
- Registering a new tab
- Making the custom tab work
- Adjusting the wait
- Example
Registering a new tab
Register a new tab via the registerTab
method.
<div id = "uploader-placeholder" > Uploading. Delight wait... </div > <script > function favoriteFiles ( container, button, dialogApi, settings ) { ... } uploadcare. registerTab ( 'favorites' , favoriteFiles) ; uploadcare. openPanel ( '#uploader-placeholder' , cypher , { tabs: 'favorites file facebook dropbox gdrive instagram vk' , favoriteFiles: [ ... ] } ) ; </script >
html
Coding tab'due south actions
Once the tab is registered, write a custom code. The post-obit lawmaking will display uploaded images made with this File Uploader case. It'll laissez passer a listing of file UUIDs with the settings
object. When a user selects a file for uploading, the file info can be passed to the dialog using dialogApi
.
function favoriteFiles ( container, button, dialogApi, settings ) { $. each (settings.favoriteFiles, role ( 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) ] ) } ) ) ; } ) ; }
javascript
Adjusting the expect
Customize your custom tab'due south look via CSS. Apply <svg>
and <symbol>
elements:
<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.iv L 21.454 18.965 L 28 13.292 50 19.37 12.552 L 16 4.6 Fifty 12.629 12.552 L 4 xiii.292 L ten.546 eighteen.965 L 8.584 27.4 Z" /> </symbol > </svg >
html
.uploadcare--menu__item_tab_favorites.uploadcare--menu__item_current { colour : #f0cb3c; }
css
Custom tab in action
Here's a live example of the File Uploader with the custom tab we've just created. Information technology displays images uploaded with this File Uploader instance:
Multiple File Uploading
Uploadcare File Uploader allows yous to upload multiple files in i go. Each file volition have its tiny progress bar and a preview when information technology'due south uploaded.
File Uploader will display individual errors if some files couldn't exist uploaded (eastward.thousand., due to size or format validation failure) and it won't affect the residue of the upload.
Enable batch uploading
Enable batch file uploading with the information-multiple
aspect in the File Uploader <input>
element.
<input type = "hidden" role = "uploadcare-uploader" proper name = "my_files" data-multiple = "true" />
html
Cheque out multiple file uploading:
Multiple file uploads are stored as file groups with corresponding group_id
as opposed to single file UUIDs.
Automatically resize uploaded images
Uploadcare File Uploader lets you lot accept hi-res images and shrink them in size to a reasonable resolution, keeping the original aspect ratio.
Benefits of automated epitome resize on upload:
- Users don't need to downscale images on their devices to meet the uploading requirements.
- Optimized storage.
- Faster uploading.
Use the data-paradigm-shrink
option to apply client-side image resize with values like:
-
800x600
, shrinks images to 0.48 megapixels with the default JPEG quality of 80% (default, when not set). -
1600x1600 95%
, shrinks images to ii.v megapixels with the JPEG quality set to 95%.
Specs and limits
The output resolution limit for data-prototype-shrink
is 268 MP (e.m., 16384x16384
). It conforms to the maximum resolution that WebKit desktop browsers back up. We recommend not to use values greater than sixteen.7 MP (4096x4096
), because it's a electric current limit for iOS devices.
Uploaded images won't be shrunk in the following cases:
- When a customer browser doesn't support a specified output resolution.
- For images uploaded from social media and URLs.
- If the
original resolution
is less than 2x larger than thetarget resolution
. For example, it won't compress a 2560x1560px (4 MP) paradigm to 1600x1600px (two.5 MP). It volition piece of work if you had a 2448x3264px (eight MP) input image. This limitation preserves an optimal image quality and file size balance. - If the paradigm color way is CMYK.
The output format will be JPEG by default unless your input paradigm has an blastoff channel (transparency). In this instance, PNG will be used instead. Grayscale images will be converted to RGB.
EXIF and ICC profile info is copied every bit-is and includes an original image orientation, camera model, geolocation, and other settings of an original image.
Resize to 1 MP on a customer side:
<input blazon = "hidden" part = "uploadcare-uploader" proper noun = "my_file" information-preview-step = " " information-image-compress = "1024x1024" />
html
Resize multiple files to 0.4 MP on a customer side:
<input blazon = "hidden" role = "uploadcare-uploader" proper noun = "my_files" information-multiple = " " information-paradigm-compress = "640x480" />
html
Localization
Uploadcare File Uploader is highly customizable and implements UI localization and custom pluralization rules. With
locales, you tin make your app instantly arrange 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
u.k.
6
zhTW
zh
You can either set an existing locale or add a custom 1 along with its pluralization rules.
Adding a locale
You can add your localization, if there's no one yet, past forking the principal File Uploader repo and adding a new localization file to this list.
Some other selection is overriding specific locale items in your global File Uploader configuration:
UPLOADCARE_LOCALE = 'en' ; UPLOADCARE_LOCALE_TRANSLATIONS = { buttons: { cancel: 'Cancel' , remove: 'Remove' , choose: { files: { one: 'Choose a file' , other: 'Choice files' } , images: { one: 'Choose an paradigm' , other: 'Load images' } } } } ;
javascript
The default is an English locale. If a string item is missing in a locale y'all created or customized, English will be a fallback.
Uploading errors tin as well be redefined in the locale. Yous can see the reference hither.
Pluralization rules
Pluralization rules may vary in different languages. In the English locale, there'll exist "1 file"
, but "3 files"
. This rule is described under the file:
key in the locale file.
Strings with quantitative values are based on what a pluralization function returns. You'll pass a number into a function, and it'll output a subkey related to your input.
function pluralize ( number ) { // do something return 'some_subkey' ; }
javascript
There are 2 subkeys for the English language localization: one
and the other
. However, it tin can get more than complex with other languages. For example, have a look at the file:
subkeys for the Russian locale. The %1
sequence is used 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 lot can ascertain a custom pluralization role 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: 'Merely %one files. Upload more.' , many: '%ane files!! That\'s a lot.' } } ; UPLOADCARE_LOCALE_PLURALIZE = function ( n ) { if (n === 1 ) return 'one' ; if (north > i && due north <= x ) return 'some' ; return 'many' ; } ;
javascript
Styling
Uploadcare File Uploader tin can exist easily integrated into your production and friction match your website await or a web app'due south UI.
Scaling File Uploader Elements
The File Uploader is designed to inherit styles from your page organically: dialog elements get scaled in line with your font size:
Times New Roman, 12px:
Courier New, 18px:
Styling With CSS
The File Uploader is thoroughly annotated with CSS classes. It'south your starting indicate into deeper customization. Yous can notice a class for every File Uploader item by inspecting its elements or sifting through the File Uploader source code.
The File Uploader dialog window expect can be customized via the uploadcare--dialog
form.
Changing Uploader Button Color
Changing the button color is one of the most mutual cases:
Button Shadow
You can add shadow and experiment with fonts and colors:
Uploading Circle Color
You lot can display the file uploading progress. The fill colour can be changed via the CSS colour
holding, while edge-color
will work for your background.
Here, yous can test the File Uploader with a customized uploading circle:
Custom Progress Bar
You tin can replace the built-in progress bar. To exercise that, you need to add a listener to the electric current File Uploader instance and get information technology in the onChange
callback. It'll exist a file object for regular File Uploaders or a grouping object for multiple File Uploaders. After that, listen to the progress
event and modify your progress bar according to the current uploadProgress
.
The following installProgressBar
function does all that. Information technology receives the ii arguments: the File Uploader instance and a progress bar DOM element. Everything else runs on CSS, animation included.
Uploaded Image Preview
The default File Uploader beliefs is to show an image preview when a user selects an image. You might want to embed this preview on your page somewhere around the File Uploader push. Such a preview could exist more than informative than simply displaying file names and sizes.
Notation, you lot have total control over the size and position of your embed. Only utilize CSS.
Image preview for a multi-file File Uploader may look differently:
You tin change the displayed images or rearrange the existing ones; all changes will so be reflected in the thumbnail list.
File Uploader Embed
User experience means the world to us. Therefore, we provide a lot of customization options that embrace both File Uploader advent and behavior.
The look of the File Uploader can be inverse via CSS, and dashboard is a nifty starting signal for decision-making your File Uploader beliefs.
Some other thing you lot can do is to embed the File Uploader every bit a panel as opposed to a default dialog window.
Embed File Uploader Using Panel
By default, the File Uploader dialog appears on a button click. The dialog will announced in a lightbox, which overlays your folio's content and dims the background.
However, you lot might want to show the File Uploader interface correct away. This advent is named panel
.
<div id = "uploader-placeholder" > Uploading. Please wait... </div > <script > uploadcare. openPanel ( '#uploader-placeholder' ) ; </script >
html
The snippet above replaces your DOM element with the uploadcare-placeholder
ID and puts it in identify once a user selects a file. This can be used to signal the uploading procedure. Likewise, the console can be closed by merely selecting a file.
Panel Styling
Like to the File Uploader dialog, the panel can be customized.
The appearance of your embed tin be changed via CSS. In this example, we remove a sharp border:
#uploader-styling { margin-top : 10px; } #uploader-styling .uploadcare--console, #uploader-styling .uploadcare--menu__item, #uploader-styling .uploadcare--menu__items { groundwork-color : transparent; border : 0; } #uploader-styling .uploadcare--panel { flex-management : column; } #uploader-styling .uploadcare--bill of fare { width : 100%; pinnacle : 60px; min-pinnacle : 60px; } #uploader-styling .uploadcare--menu__items { padding-right : 0; flex-management : row; }
css
Some dialog elements are rendered equally iframe
by Uploadcare servers, which doesn't let you customize CSS. However, we provide a set of specific methods to inject CSS into iframes.
Image crop
Cropping images is 1 of the virtually common tasks, so nosotros added information technology right in the File Uploader UI.
Uploadcare File Uploader features a good bunch of ingather options, including costless crop. Adding the characteristic to your File Uploader instance is done by implementing the data-crop
choice.
Note that it'll add an additional step of epitome editing.
How Cropping Works
Technically, image cropping works as post-processing via the Image Processing feature:
- Original images become to an Uploadcare project associated with a Public Cardinal gear up every bit your File Uploader instance.
- The crop is practical as the
crop
epitome processing functioning by injecting its URL directive into original URLs. - The File Uploader returns resulting CDN URLs with an injected
crop
.
Configuring Crop
Crop options are held within the data-crop
aspect as a comma-separated cord with presets names. When you lot 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. It tin can't be combined with other presets. -
""
or"free"
, crop is enabled. Users can freely select any crop area on their images. -
"2:three"
, any area with the aspect ratio of 2:3 can be selected for cropping. -
"300x200"
— same as above, only if the selected area is greater than 300x200 pixels, the resulting image volition be downscaled to fit the dimensions. -
"300x200 upscale"
— aforementioned as above, just even if the selected area is smaller, the resulting paradigm gets upscaled to fit the dimensions. -
"300x200 minimum"
— users won't be able to define an area smaller than 300x200 pixels. If an paradigm we apply the crop to is smaller than 300x200 pixels, information technology will be upscaled to fit the dimensions.
Ingather examples
Free crop:
<input type = "hidden" office = "uploadcare-uploader" name = "my_file" information-crop = " " />
html
Choosing from predefined attribute ratios:
<input blazon = "subconscious" role = "uploadcare-uploader" proper noun = "my_file" data-ingather = "gratis, 16:9, 4:3, v:iv, 1:one" />
html
Fixed attribute ratio:
<input type = "hidden" part = "uploadcare-uploader" name = "my_file" data-crop = "4:3" />
html
Fixed size with upscaling:
<input type = "subconscious" role = "uploadcare-uploader" name = "my_file" information-ingather = "400x300 upscale" />
html
Default files in Uploader dialog
Uploadcare File Uploader allows you to make specified files announced in the File Uploader dialog on open.
Specify these files by adding the value
attribute to your File Uploader <input>
chemical 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 case, setting it to a file UUID or a CDN URL volition result in that the file is loaded into the File Uploader. You tin can utilize it someday, and it'll take effect immediately.
Hither'south how you do it:
You may also want to cheque out a live example:
JS snippets and CSS tricks
In this cookbook part, you can detect popular code examples and resolutions of mutual tasks when working with File Uploader. Less words, more code!
Paste an image from the clipboard
const widget = uploadcare. Widget ( "[office=uploadcare-uploader]" ) ; widget. onDialogOpen ( ( dialog ) => { function uploadFromClipboard ( due east ) { allow data = e.clipboardData; if ( ! !information && ! !data.items.length) { // check if clipboard data is image if (data.items[ 0 ] .type. indexOf ( "image" ) != 0 ) { alert ( "No prototype in the clipboard" ) ; return ; } let hulk = e.clipboardData.items[ 0 ] . getAsFile ( ) ; dialog. addFiles ( "object" , [blob] ) ; } } window. addEventListener ( "paste" , uploadFromClipboard) ; } ) ;
javascript
Get a CDN URL of an uploaded file
For a single-upload widget.
// get a widget reference const widget = uploadcare. SingleWidget ( "[role=uploadcare-uploader]" ) ; // mind to the "upload completed" event widget. onUploadComplete ( fileInfo => { // get a CDN URL from the file info console. log (fileInfo.cdnUrl) ; } ) ;
javascript
Go CDN URLs of uploaded files
For a multi-upload widget.
// get a widget reference const widget = uploadcare. MultipleWidget ( "[function=uploadcare-uploader]" ) ; // listen to the "alter" event widget. onChange ( office ( group ) { // get a list of file instances group. files ( ) . forEach ( file => { // in one case each file is uploaded, get its CDN URL from the fileInfo object file. done ( fileInfo => { console. log (fileInfo.cdnUrl) ; } ) ; } ) ; } ) ;
javascript
Get a group CDN URL
For a multi-upload widget.
// go 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) ; } ) ;
javascript
Get a CDN URL of an uploaded file/grouping
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 grouping instance dialog. done ( res => { // once a file or group is uploaded, get its CDN URL res. hope ( ) . washed ( info => { console. log (info.cdnUrl) ; } ) ; } ) ;
javascript
Get a camera-recorded video elapsing
// get widget reference const widget = uploadcare. Widget ( "[role=uploadcare-uploader]" ) ; let cameraRecDuration = aught ; let recStart = naught ; 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 Appointment ( ) . getTime ( ) ; } // user clicks "finish recording" if (e.target.classList. contains ( "uploadcare--camera__button_type_stop-record" ) ) { recEnd = new Date ( ) . getTime ( ) ; cameraRecDuration = (recEnd - recStart) / chiliad ; console. log ( "Duration: " , cameraRecDuration) ; } } ) ;
javascript
Check if a file was added or removed
// go widget reference const widget = uploadcare. Widget ( "[role=uploadcare-uploader]" ) // become dialog object to access its API widget. onDialogOpen ( dialog => { // listen to "file added" issue dialog.fileColl.onAdd. add together ( file => { console. log ( "File added" , file) } ) ; // heed to "file removed" effect dialog.fileColl.onRemove. add together ( file => { console. log ( "File removed" , file) } ) ; } ) ;
javascript
Get the upload source
// go widget reference const widget = uploadcare. Widget ( "[function=uploadcare-uploader]" ) ; // listen to the "upload completed" event widget. onUploadComplete ( fileInfo => { // get source details from file information panel. log (fileInfo.sourceInfo.source) ; } ) ;
javascript
Add together an overlay to the crop
.uploadcare--jcrop-tracker::afterwards { content : "" ; position : absolute; width : 100%; height : 100%; left : 0; /* URL of the overlay image */ groundwork-epitome : url (<https://i.imgur.com/hSbF6v0.png>) ; background-size : encompass; background-position : eye; } .uploadcare--jcrop-tracker:first-of-blazon { opacity : 1 !of import ; groundwork-color : transparent !important ; }
css
Get a selected crop preset
<input blazon = "hidden" role = "uploadcare-uploader" proper noun = "my_file" id = "uploadcare-file" data-ingather = "two:3, 5:6, sixteen:9" />
html
let currentPreset = '2:3' ; document. addEventListener ( 'click' , eastward => { // user clicks on a crop preset icon if (eastward.target.classList. contains ( 'uploadcare--crop-sizes__item' ) || due east.target.classList. contains ( 'uploadcare--crop-sizes__icon' ) ) { // become the caption of the preset selected currentPreset = document. querySelector ( '.uploadcare--crop-sizes__item_current' ) .dataset.caption; console. log (currentPreset) ; } } ) ;
javascript
Upload an epitome from Base64
// original base64 epitome const b64data = "data:prototype/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" ; // convert dataURI to a File object function dataURLtoFile ( dataurl, filename ) { let arr = dataurl. carve up ( ',' ) , mime = arr[ 0 ] . match ( / :(.*?); / ) [ ane ] , bstr = atob (arr[ ane ] ) , n = bstr.length, u8arr = new Uint8Array (n) ; while (n-- ) { u8arr[n] = bstr. charCodeAt (northward) ; } render new File ( [u8arr] , filename, {type:mime} ) ; } // convert a base64 paradigm 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) ; } ) ;
javascript
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 together the thumbnail to the page document.body. appendChild (preview) ; } ) ;
javascript
Add custom names to crop presets
<input blazon = "hidden" function = "uploadcare-uploader" proper noun = "my_file" id = "uploadcare-file" data-crop = "complimentary,1:one,2:3" />
html
.uploadcare--ingather-sizes__item { overflow : visible; } .uploadcare--crop-sizes__item:nth-kid(1)::after { content : "Free form" ; } .uploadcare--crop-sizes__item:nth-kid(2)::after { content : "Square" ; } .uploadcare--crop-sizes__item:nth-child(3)::afterwards { content : "Portrait" ; }
css
Add custom widget button labels
<input blazon = "hidden" role = "uploadcare-uploader" id = "uploadcare-file-i" data-btn-text = "I'm the first buton" /> <input type = "hidden" role = "uploadcare-uploader" id = "uploadcare-file-2" information-btn-text = "I'm the second one" /> <input blazon = "hidden" office = "uploadcare-uploader" id = "uploadcare-file-3" data-btn-text = "And I am the 3rd" />
html
// get an assortment 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" ) ; } ) ;
javascript
Reset widget afterwards upload
// get widget reference const widget = uploadcare. Widget ( "[part=uploadcare-uploader]" ) ; // once a file is uploaded, output its URL and reset the widget widget. onUploadComplete ( fileInfo => { console. log (fileInfo.cdnUrl) ; widget. value ( null ) ; } ) ;
javascript
Add together a custom message to the dialog
/* turn the "later on" pseudo element of the dialog container'due south div into a hint */ .uploadcare--tab__content::afterward { content : "Wake upwards Neo... The Matrix has y'all... Follow the white rabbit🐇" ; padding : 1em; margin : 2em; background-color : #000; colour : #00ff00; border-radius : 5px; }
css
Video record time limit
const SECOND = 1000 ; // record time limit const TIME_LIMIT = 5 * 2d ; const widget = uploadcare. Widget ( "[role=uploadcare-uploader]" ) ; widget. onDialogOpen ( ( dialog ) => { // Mind to a click on the Start push dialog.dialogElement[ 0 ] . addEventListener ( "click" , ( e ) => { if ( e.target.classList. contains ( "uploadcare--camera__button_type_start-record" ) ) { const stopBtn = dialog.dialogElement[ 0 ] . querySelector ( ".uploadcare--camera__button_type_stop-record" ) ; // Diasplay countdown on Finish button permit remaining = TIME_LIMIT ; stopBtn.innerText = ` End (in ${remaining / 1000 } due south) ` ; let counter = setInterval ( ( ) => { remaining -= 1000 ; if (remaining <= 0 ) { clearInterval (counter) ; } stopBtn.innerText = ` Stop ( ${remaining / thousand } s) ` ; } , 1000 ) ; // Click End push (finish recording) later on TIME_LIMIT setTimeout ( ( ) => { stopBtn. click ( ) ; } , TIME_LIMIT ) ; } } ) ; } ) ;
javascript
Versioning
When we innovate backward-incompatible changes, we release new major versions. Once published, such versions are supported for 2 years. Y'all will still be able to utilise any file uploader version later its support term at your own take chances.
Version | Engagement Published | Supported Until |
---|---|---|
3.x | 28 Jun 2017 | TBD |
2.x | twenty Feb 2015 | one Jan 2020 |
1.x | 21 Mar 2014 | 1 Jun 2019 |
0.ten | 6 Sep 2012 | 1 Jun 2019 |
Source: https://uploadcare.com/docs/uploads/file-uploader/
Postar um comentário for "Adding Custom Data During Uploading Jqueryfile Upload"