123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635 |
- ---
- sidebar_position: 3
- slug: /uppy
- ---
- import Tabs from '@theme/Tabs';
- import TabItem from '@theme/TabItem';
- import UppyCdnExample from '/src/components/UppyCdnExample';
- # Uppy core
- Uppy can be an uploader and an interface with a lot of features. Features can be
- added incrementally with plugins, but Uppy can be as bare bones as you want it
- to be. So we build Uppy’s heart, `@uppy/core`, as a standalone orchestrator. It
- acts as a state manager, event emitter, and restrictions handler.
- ## When should I use it?
- `@uppy/core` is the fundament of the Uppy ecosystem, the orchestrator for all
- added plugins. No matter the uploading experience you’re looking for, it all
- starts with installing this plugin.
- You can use `@uppy/core` and
- [build your own UI](/docs/guides/building-your-own-ui-with-uppy) or go for the
- [Dashboard](/docs/dashboard) integration. For an uploading plugin, you can refer
- to [choosing the uploader you need](/docs/guides/choosing-uploader).
- If you want to see how it all comes together, checkout the
- [examples](/examples).
- ## Install
- <Tabs>
- <TabItem value="npm" label="NPM" default>
- ```shell
- npm install @uppy/core
- ```
- </TabItem>
- <TabItem value="yarn" label="Yarn">
- ```shell
- yarn add @uppy/core
- ```
- </TabItem>
- <TabItem value="cdn" label="CDN">
- <UppyCdnExample>
- {`
- import { Uppy } from "{{UPPY_JS_URL}}"
- const uppy = new Uppy()
- `}
- </UppyCdnExample>
- </TabItem>
- </Tabs>
- ## Use
- `@uppy/core` has four exports: `Uppy`, `UIPlugin`, `BasePlugin`, and
- `debugLogger`. The default export is the `Uppy` class.
- ### Working with Uppy files
- Uppy keeps files in state with the [`File`][] browser API, but it’s wrapped in
- an `Object` to be able to add more data to it, which we call an _Uppy file_. All
- these properties can be useful for plugins and side-effects (such as
- [events](#events)).
- Mutating these properties should be done through [methods](#methods).
- <details>
- <summary>Uppy file properties</summary>
- #### `file.source`
- Name of the plugin that was responsible for adding this file. Typically a remote
- provider plugin like `'GoogleDrive'` or a UI plugin like `'DragDrop'`.
- #### `file.id`
- Unique ID for the file.
- #### `file.name`
- The name of the file.
- #### `file.meta`
- Object containing standard as well as user-defined metadata for each file. Any
- custom file metadata should be JSON-serializable. The following standard
- metadata will be stored on all file objects, but plugins may add more metadata.
- - `file.meta.name`
- - Same as `file.name`.
- - `file.meta.type`
- - Same as `file.type`.
- - `file.meta.relativePath`
- - For any local folder that was drag-dropped or opened in Uppy, the files
- inside the folder will have the `relativePath` metadata field set to their
- path, relative to the folder. `relativePath` begins with the folder’s name
- and ends with the file’s name. If opening or drag-dropping a file instead of
- a folder, `relativePath` will be `null`. The same behaviour exists for
- remote (provider) files, but the path will instead be relative to the user’s
- selection (checkboxes). No leading or trailing slashes.
- - **Local file example:** When drag-dropping a local folder `folder1` which
- has a folder inside of it named `folder2` which has a file named `file`
- inside of it, the `relativePath` meta field of the file will be
- `folder1/folder2/file`. However if drag-dropping or opening `file` directly,
- `relativePath` will be `null`.
- - **Remote file example:** Suppose we have a remote provider folder structure
- such as `/folder1/folder2/file`. Then, if the user checks the checkbox next
- to `folder1`, `file`’s `relativePath` will be `"folder1/folder2/file"`.
- However if the user first navigates into `folder1`, and only then checks the
- checkbox next to `folder2`, `relativePath` will be `"folder2/file"`.
- - `file.meta.absolutePath`
- - The `absolutePath` meta field will only be set for remote files. Regardless
- of user selection, it will always be the path relative to the root of the
- provider’s list of files, as presented to the user. `absolutePath` always
- begins with a `/` and will always end with the file’s name. To clarify: The
- difference between `absolutePath` and `relativePath` is that `absolutePath`
- only exists for remote files, and always has the full path to the file,
- while `relativePath` is the file’s path _relative to the user’s selected
- folder_.
- #### `file.type`
- MIME type of the file. This may actually be guessed if a file type was not
- provided by the user’s browser, so this is a best-effort value and not
- guaranteed to be correct.
- #### `file.data`
- For local files, this is the actual [`File`][] or [`Blob`][] object representing
- the file contents.
- For files that are imported from remote providers, the file data is not
- available in the browser.
- [`file`]: https://developer.mozilla.org/en-US/docs/Web/API/File
- [`blob`]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
- #### `file.progress`
- An object with upload progress data.
- **Properties**
- - `bytesUploaded` - Number of bytes uploaded so far.
- - `bytesTotal` - Number of bytes that must be uploaded in total.
- - `uploadStarted` - Null if the upload has not started yet. Once started, this
- property stores a UNIX timestamp. Note that this is only set _after_
- preprocessing.
- - `uploadComplete` - Boolean indicating if the upload has completed. Note this
- does _not_ mean that postprocessing has completed, too.
- - `percentage` - Integer percentage between 0 and 100.
- #### `file.size`
- Size in bytes of the file.
- #### `file.isRemote`
- Boolean: is this file imported from a remote provider?
- #### `file.remote`
- Grab bag of data for remote providers. Generally not interesting for end users.
- #### `file.preview`
- An optional URL to a visual thumbnail for the file.
- #### `file.uploadURL`
- When an upload is completed, this may contain a URL to the uploaded file.
- Depending on server configuration it may not be accessible or correct.
- </details>
- ## `new Uppy(options?)`
- ```js
- import Uppy from '@uppy/core';
- const uppy = new Uppy();
- ```
- ### Options
- #### `id`
- A site-wide unique ID for the instance (`string`, default: `uppy`).
- :::note
- If several Uppy instances are being used, for instance, on two different pages,
- an `id` should be specified. This allows Uppy to store information in
- `localStorage` without colliding with other Uppy instances.
- This ID should be persistent across page reloads and navigation—it shouldn’t be
- a random number that is different every time Uppy is loaded.
- :::
- #### `autoProceed`
- Upload as soon as files are added (`boolean`, default: `false`).
- By default Uppy will wait for an upload button to be pressed in the UI, or the
- `.upload()` method to be called before starting an upload. Setting this to
- `true` will start uploading automatically after the first file is selected
- #### `allowMultipleUploadBatches`
- Whether to allow several upload batches (`boolean`, default: `true`).
- This means several calls to `.upload()`, or a user adding more files after
- already uploading some. An upload batch is made up of the files that were added
- since the earlier `.upload()` call.
- With this option set to `true`, users can upload some files, and then add _more_
- files and upload those as well. A model use case for this is uploading images to
- a gallery or adding attachments to an email.
- With this option set to `false`, users can upload some files, and you can listen
- for the [`'complete'`](#complete) event to continue to the next step in your
- app’s upload flow. A typical use case for this is uploading a new profile
- picture. If you are integrating with an existing HTML form, this option gives
- the closest behaviour to a bare `<input type="file">`.
- #### `debug`
- Whether to send debugging and warning logs (`boolean`, default: `false`).
- Setting this to `true` sets the [`logger`](#logger) to
- [`debugLogger`](#debuglogger).
- #### `logger`
- Logger used for [`uppy.log`](#logmessage-type) (`Object`, default:
- `justErrorsLogger`).
- By providing your own `logger`, you can send the debug information to a server,
- choose to log errors only, etc.
- :::note
- Set `logger` to [`debugLogger`](#debuglogger) to get debug info output to the
- browser console:
- :::
- :::note
- You can also provide your own logger object: it should expose `debug`, `warn`
- and `error` methods, as shown in the examples below.
- Here’s an example of a `logger` that does nothing:
- ```js
- const nullLogger = {
- debug: (...args) => {},
- warn: (...args) => {},
- error: (...args) => {},
- };
- ```
- :::
- #### `restrictions`
- Conditions for restricting an upload (`Object`, default: `{}`).
- | Property | Value | Description |
- | -------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
- | `maxFileSize` | `number` | maximum file size in bytes for each individual file |
- | `minFileSize` | `number` | minimum file size in bytes for each individual file |
- | `maxTotalFileSize` | `number` | maximum file size in bytes for all the files that can be selected for upload |
- | `maxNumberOfFiles` | `number` | total number of files that can be selected |
- | `minNumberOfFiles` | `number` | minimum number of files that must be selected before the upload |
- | `allowedFileTypes` | `Array` | wildcards `image/*`, or exact mime types `image/jpeg`, or file extensions `.jpg`: `['image/*', '.jpg', '.jpeg', '.png', '.gif']` |
- | `requiredMetaFields` | `Array<string>` | make keys from the `meta` object in every file required before uploading |
- :::note
- `maxNumberOfFiles` also affects the number of files a user is able to select via
- the system file dialog in UI plugins like `DragDrop`, `FileInput` and
- `Dashboard`. When set to `1`, they will only be able to select a single file.
- When `null` or another number is provided, they will be able to select several
- files.
- :::
- :::note
- `allowedFileTypes` gets passed to the file system dialog via the
- [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Limiting_accepted_file_types)
- accept attribute, so only types supported by the browser will work.
- :::
- :::tip
- If you’d like to force a certain meta field data to be entered before the
- upload, you can
- [do so using `onBeforeUpload`](https://github.com/transloadit/uppy/issues/1703#issuecomment-507202561).
- :::
- :::tip
- If you need to restrict `allowedFileTypes` to a file extension with double dots,
- like `.nii.gz`, you can do so by
- [setting `allowedFileTypes` to the last part of the extension, `allowedFileTypes: ['.gz']`, and then using `onBeforeFileAdded` to filter for `.nii.gz`](https://github.com/transloadit/uppy/issues/1822#issuecomment-526801208).
- :::
- #### `meta`
- Key/value pairs to add to each file’s `metadata` (`Object`, default: `{}`).
- :::note
- Metadata from each file is then attached to uploads in the [Tus](/docs/tus) and
- [XHR](/docs/xhr-upload) plugins.
- :::
- :::info
- Two methods also exist for updating `metadata`: [`setMeta`](#setmetadata) and
- [`setFileMeta`](#setfilemetafileid-data).
- :::
- :::info
- Metadata can also be added from a `<form>` element on your page, through the
- [Form](#) plugin or through the UI if you are using Dashboard with the
- [`metaFields`](/docs/dashboard#metafields) option.
- :::
- <i id="onBeforeFileAdded" />
- #### `onBeforeFileAdded(file, files)`
- A function called before a file is added to Uppy (`Function`, default:
- `(files, file) => !Object.hasOwn(files, file.id)`).
- Use this function to run any number of custom checks on the selected file, or
- manipulate it, for instance, by optimizing a file name. You can also allow
- duplicate files with this.
- You can return `true` to keep the file as is, `false` to remove the file, or
- return a modified file.
- :::caution
- This method is intended for quick synchronous checks and modifications only. If
- you need to do an async API call, or heavy work on a file (like compression or
- encryption), you should use a [custom plugin](/docs/guides/building-plugins)
- instead.
- :::
- :::info
- No notification will be shown to the user about a file not passing validation by
- default. We recommend showing a message using
- [`uppy.info()`](#infomessage-type-duration) and logging to console for debugging
- purposes via [`uppy.log()`](#logmessage-type).
- :::
- <details>
- <summary>Filter, change, and abort example</summary>
- Allow all files, also duplicate files. This will replace the file if it has not
- been uploaded. If you upload a duplicate file again it depends on your upload
- plugin and backend how it is handled.
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeFileAdded: () => true,
- ```
- Keep only files under a condition:
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeFileAdded: (currentFile, files) => {
- if (currentFile.name === 'forest-IMG_0616.jpg') {
- return true
- }
- return false
- },
- ```
- Change all file names:
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeFileAdded: (currentFile, files) => {
- const modifiedFile = {
- ...currentFile,
- name: `${currentFile.name}__${Date.now()}`,
- }
- return modifiedFile
- },
- ```
- Abort a file:
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeFileAdded: (currentFile, files) => {
- if (!currentFile.type) {
- // log to console
- uppy.log(`Skipping file because it has no type`);
- // show error message to the user
- uppy.info(`Skipping file because it has no type`, 'error', 500);
- return false;
- }
- },
- });
- ```
- </details>
- #### `onBeforeUpload(files)`
- A function called before when upload is initiated (`Function`, default:
- `(files) => files`).
- Use this to check if all files or their total number match your requirements, or
- manipulate all the files at once before upload.
- You can return `true` to continue the upload, `false` to cancel it, or return
- modified files.
- :::caution
- This method is intended for quick synchronous checks and modifications only. If
- you need to do an async API call, or heavy work on a file (like compression or
- encryption), you should use a [custom plugin](/docs/guides/building-plugins)
- instead.
- :::
- :::info
- No notification will be shown to the user about a file not passing validation by
- default. We recommend showing a message using
- [`uppy.info()`](#infomessage-type-duration) and logging to console for debugging
- purposes via [`uppy.log()`](#logmessage-type).
- :::
- <details>
- <summary>Change and abort example</summary>
- Change all file names:
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeUpload: (files) => {
- // We’ll be careful to return a new object, not mutating the original `files`
- const updatedFiles = {};
- Object.keys(files).forEach((fileID) => {
- updatedFiles[fileID] = {
- ...files[fileID],
- name: `${myCustomPrefix}__${files[fileID].name}`,
- };
- });
- return updatedFiles;
- },
- });
- ```
- Abort an upload:
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeUpload: (files) => {
- if (Object.keys(files).length < 2) {
- // log to console
- uppy.log(
- `Aborting upload because only ${
- Object.keys(files).length
- } files were selected`,
- );
- // show error message to the user
- uppy.info(`You have to select at least 2 files`, 'error', 500);
- return false;
- }
- return true;
- },
- });
- ```
- </details>
- #### `locale`
- You can override locale strings by passing the `strings` object with the keys
- you want to override.
- :::note
- Array indexed objects are used for pluralisation.
- :::
- :::info
- If you want a different language it’s better to use [locales](/docs/locales).
- :::
- ```js
- module.exports = {
- strings: {
- addBulkFilesFailed: {
- 0: 'Failed to add %{smart_count} file due to an internal error',
- 1: 'Failed to add %{smart_count} files due to internal errors',
- },
- youCanOnlyUploadX: {
- 0: 'You can only upload %{smart_count} file',
- 1: 'You can only upload %{smart_count} files',
- },
- youHaveToAtLeastSelectX: {
- 0: 'You have to select at least %{smart_count} file',
- 1: 'You have to select at least %{smart_count} files',
- },
- exceedsSize: '%{file} exceeds maximum allowed size of %{size}',
- missingRequiredMetaField: 'Missing required meta fields',
- missingRequiredMetaFieldOnFile:
- 'Missing required meta fields in %{fileName}',
- inferiorSize: 'This file is smaller than the allowed size of %{size}',
- youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
- noMoreFilesAllowed: 'Cannot add more files',
- noDuplicates:
- "Cannot add the duplicate file '%{fileName}', it already exists",
- companionError: 'Connection with Companion failed',
- authAborted: 'Authentication aborted',
- companionUnauthorizeHint:
- 'To unauthorize to your %{provider} account, please go to %{url}',
- failedToUpload: 'Failed to upload %{file}',
- noInternetConnection: 'No Internet connection',
- connectedToInternet: 'Connected to the Internet',
- // Strings for remote providers
- noFilesFound: 'You have no files or folders here',
- selectX: {
- 0: 'Select %{smart_count}',
- 1: 'Select %{smart_count}',
- },
- allFilesFromFolderNamed: 'All files from folder %{name}',
- openFolderNamed: 'Open folder %{name}',
- cancel: 'Cancel',
- logOut: 'Log out',
- filter: 'Filter',
- resetFilter: 'Reset filter',
- loading: 'Loading...',
- authenticateWithTitle:
- 'Please authenticate with %{pluginName} to select files',
- authenticateWith: 'Connect to %{pluginName}',
- signInWithGoogle: 'Sign in with Google',
- searchImages: 'Search for images',
- enterTextToSearch: 'Enter text to search for images',
- search: 'Search',
- emptyFolderAdded: 'No files were added from empty folder',
- folderAlreadyAdded: 'The folder "%{folder}" was already added',
- folderAdded: {
- 0: 'Added %{smart_count} file from %{folder}',
- 1: 'Added %{smart_count} files from %{folder}',
- },
- },
- };
- ```
- #### `store`
- The store that is used to keep track of internal state (`Object`, default:
- [`DefaultStore`](/docs/guides/custom-stores)).
- This option can be used to plug Uppy state into an external state management
- library, such as [Redux](/docs/guides/custom-stores).
- {/* TODO document store API */}
- #### `infoTimeout`
- How long an [Informer](/docs/informer) notification will be visible (`number`,
- default: `5000`).
- ### Methods
- #### `use(plugin, opts)`
- Add a plugin to Uppy, with an optional plugin options object.
- ```js
- import Uppy from '@uppy/core';
- import DragDrop from '@uppy/drag-drop';
- const uppy = new Uppy();
- uppy.use(DragDrop, { target: 'body' });
- ```
- #### `removePlugin(instance)`
- Uninstall and remove a plugin.
- #### `getPlugin(id)`
- Get a plugin by its `id` to access its methods.
- #### `getID()`
- Get the Uppy instance ID, see the [`id`](#id) option.
- #### `addFile(file)`
- Add a new file to Uppy’s internal state. `addFile` will return the generated id
- for the file that was added.
- `addFile` gives an error if the file cannot be added, either because
- `onBeforeFileAdded(file)` gave an error, or because `uppy.opts.restrictions`
- checks failed.
- ```js
- uppy.addFile({
- name: 'my-file.jpg', // file name
- type: 'image/jpeg', // file type
- data: blob, // file blob
- meta: {
- // optional, store the directory path of a file so Uppy can tell identical files in different directories apart.
- relativePath: webkitFileSystemEntry.relativePath,
- },
- source: 'Local', // optional, determines the source of the file, for example, Instagram.
- isRemote: false, // optional, set to true if actual file is not in the browser, but on some remote server, for example,
- // when using companion in combination with Instagram.
- });
- ```
- :::note
- If you try to add a file that already exists, `addFile` will throw an error.
- Unless that duplicate file was dropped with a folder — duplicate files from
- different folders are allowed, when selected with that folder. This is because
- we add `file.meta.relativePath` to the `file.id`.
- :::
- :::info
- Checkout [working with Uppy files](#working-with-uppy-files).
- :::
- :::info
- If `uppy.opts.autoProceed === true`, Uppy will begin uploading automatically
- when files are added.
- :::
- :::info
- Sometimes you might need to add a remote file to Uppy. This can be achieved by
- [fetching the file, then creating a Blob object, or using the Url plugin with Companion](https://github.com/transloadit/uppy/issues/1006#issuecomment-413495493).
- :::
- :::info
- Sometimes you might need to mark some files as “already uploaded”, so that the
- user sees them, but they won’t actually be uploaded by Uppy. This can be
- achieved by
- [looping through files and setting `uploadComplete: true, uploadStarted: true` on them](https://github.com/transloadit/uppy/issues/1112#issuecomment-432339569)
- :::
- #### `removeFile(fileID)`
- Remove a file from Uppy. Removing a file that is already being uploaded cancels
- that upload.
- ```js
- uppy.removeFile('uppyteamkongjpg1501851828779');
- ```
- #### `clearUploadedFiles()`
- Clear the state. Can be useful for manually resetting Uppy after a successful
- upload.
- Upload plugins may choose to throw an error if called during an upload.
- #### `getFile(fileID)`
- Get a specific [Uppy file](#working-with-uppy-files) by its ID.
- ```js
- const file = uppy.getFile('uppyteamkongjpg1501851828779');
- ```
- #### `getFiles()`
- Get an array of all added [Uppy files](#working-with-uppy-files).
- ```js
- const files = uppy.getFiles();
- ```
- #### `upload()`
- Start uploading added files.
- Returns a Promise `result` that resolves with an object containing two arrays of
- uploaded files:
- - `result.successful` - Files that were uploaded successfully.
- - `result.failed` - Files that did not upload successfully. These files will
- have a `.error` property describing what went wrong.
- ```js
- uppy.upload().then((result) => {
- console.info('Successful uploads:', result.successful);
- if (result.failed.length > 0) {
- console.error('Errors:');
- result.failed.forEach((file) => {
- console.error(file.error);
- });
- }
- });
- ```
- #### `pauseResume(fileID)`
- Toggle pause/resume on an upload. Will only work if resumable upload plugin,
- such as [Tus](/docs/tus/), is used.
- #### `pauseAll()`
- Pause all uploads. Will only work if a resumable upload plugin, such as
- [Tus](/docs/tus/), is used.
- #### `resumeAll()`
- Resume all uploads. Will only work if resumable upload plugin, such as
- [Tus](/docs/tus/), is used.
- #### `retryUpload(fileID)`
- Retry an upload (after an error, for example).
- #### `retryAll()`
- Retry all uploads (after an error, for example).
- #### `cancelAll({ reason: 'user' })`
- | Argument | Type | Description |
- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
- | `reason` | `string` | The reason for canceling. Plugins can use this to provide different cleanup behavior (Transloadit plugin cancels an Assembly if user clicked on the “cancel” button). Possible values are: `user` (default) - The user has pressed “cancel”; `unmount` - The Uppy instance has been closed programmatically |
- Cancel all uploads, reset progress and remove all files.
- #### `setState(patch)`
- Update Uppy’s internal state. Usually, this method is called internally, but in
- some cases it might be useful to alter something directly, especially when
- implementing your own plugins.
- Uppy’s default state on initialization:
- ```js
- const state = {
- plugins: {},
- files: {},
- currentUploads: {},
- capabilities: {
- resumableUploads: false,
- },
- totalProgress: 0,
- meta: { ...this.opts.meta },
- info: {
- isHidden: true,
- type: 'info',
- message: '',
- },
- };
- ```
- Updating state:
- ```js
- uppy.setState({ smth: true });
- ```
- :::note
- State in Uppy is considered to be immutable. When updating values, make sure not
- mutate them, but instead create copies. See
- [Redux docs](http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html)
- for more info on this.
- :::
- #### `getState()`
- Returns the current state from the [Store](#store).
- #### `setFileState(fileID, state)`
- Update the state for a single file. This is mostly useful for plugins that may
- want to store data on [Uppy files](#working-with-uppy-files), or need to pass
- file-specific configurations to other plugins that support it.
- `fileID` is the string file ID. `state` is an object that will be merged into
- the file’s state object.
- #### `setMeta(data)`
- Alters global `meta` object in state, the one that can be set in Uppy options
- and gets merged with all newly added files. Calling `setMeta` will also merge
- newly added meta data with files that had been selected before.
- ```js
- uppy.setMeta({ resize: 1500, token: 'ab5kjfg' });
- ```
- #### `setFileMeta(fileID, data)`
- Update metadata for a specific file.
- ```js
- uppy.setFileMeta('myfileID', { resize: 1500 });
- ```
- #### `setOptions(opts)`
- Change the options Uppy initialized with.
- ```js
- const uppy = new Uppy();
- uppy.setOptions({
- restrictions: { maxNumberOfFiles: 3 },
- autoProceed: true,
- });
- uppy.setOptions({
- locale: {
- strings: {
- cancel: 'Отмена',
- },
- },
- });
- ```
- You can also change options for plugin:
- ```js
- // Change width of the Dashboard drag-and-drop aread on the fly
- uppy.getPlugin('Dashboard').setOptions({
- width: 300,
- });
- ```
- #### `close({ reason: 'user' })`
- | Argument | Type | Description |
- | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
- | `reason` | `string` | The reason for canceling. Plugins can use this to provide different cleanup behavior (Transloadit plugin cancels an Assembly if user clicked on the “cancel” button). Possible values are: `user` (default) - The user has pressed “cancel”; `unmount` - The Uppy instance has been closed programmatically |
- Uninstall all plugins and close down this Uppy instance. Also runs
- `uppy.cancelAll()` before uninstalling.
- #### `logout()`
- Calls `provider.logout()` on each remote provider plugin (Google Drive,
- Instagram, etc). Useful, for example, after your users log out of their account
- in your app — this will clean things up with Uppy cloud providers as well, for
- extra security.
- #### `log(message, type)`
- | Argument | Type | Description |
- | --------- | --------- | --------------------------- |
- | `message` | `string` | message to log |
- | `type` | `string?` | `debug`, `warn`, or `error` |
- See [`logger`](#logger) docs for details.
- ```js
- uppy.log('[Dashboard] adding files...');
- ```
- #### `info(message, type, duration)`
- Sets a message in state, with optional details, that can be shown by
- notification UI plugins. It’s using the [Informer](/docs/informer) plugin,
- included by default in Dashboard.
- | Argument | Type | Description |
- | ---------- | ------------------ | --------------------------------------------------------------------------------- |
- | `message` | `string`, `Object` | `'info message'` or `{ message: 'Oh no!', details: 'File couldn’t be uploaded' }` |
- | `type` | `string?` | `'info'`, `'warning'`, `'success'` or `'error'` |
- | `duration` | `number?` | in milliseconds |
- `info-visible` and `info-hidden` events are emitted when this info message
- should be visible or hidden.
- ```js
- this.info('Oh my, something good happened!', 'success', 3000);
- ```
- ```js
- this.info(
- {
- message: 'Oh no, something bad happened!',
- details:
- 'File couldn’t be uploaded because there is no internet connection',
- },
- 'error',
- 5000,
- );
- ```
- #### `addPreProcessor(fn)`
- Add a preprocessing function. `fn` gets called with a list of file IDs before an
- upload starts. `fn` should return a Promise. Its resolution value is ignored.
- :::info
- To change file data and such, use Uppy state updates, for example using
- [`setFileState`](#setfilestatefileid-state).
- :::
- #### `addUploader(fn)`
- Add an uploader function. `fn` gets called with a list of file IDs when an
- upload should start. Uploader functions should do the actual uploading work,
- such as creating and sending an XMLHttpRequest or calling into some upload
- service SDK. `fn` should return a Promise that resolves once all files have been
- uploaded.
- :::tip
- You may choose to still resolve the Promise if some file uploads fail. This way,
- any postprocessing will still run on the files that were uploaded successfully,
- while uploads that failed will be retried when [`retryAll`](#retryall) is
- called.
- :::
- #### `addPostProcessor(fn)`
- Add a postprocessing function. `fn` is called with a list of file IDs when an
- upload has finished. `fn` should return a Promise that resolves when the
- processing work is complete. The value of the Promise is ignored.
- For example, you could wait for file encoding or CDN propagation to complete, or
- you could do an HTTP API call to create an album containing all images that were
- uploaded.
- #### `removePreProcessor/removeUploader/removePostProcessor(fn)`
- Remove a processor or uploader function that was added before. Normally, this
- should be done in the [`uninstall()`](#uninstall) method.
- #### `on('event', action)`
- Subscribe to an uppy-event. See below for the full list of events.
- #### `once('event', action)`
- Create an event listener that fires once. See below for the full list of events.
- #### `off('event', action)`
- Unsubscribe to an uppy-event. See below for the full list of events.
- ### Events
- Uppy exposes events that you can subscribe to for side-effects.
- #### `file-added`
- Fired each time a file is added.
- **Parameters**
- - `file` - The [Uppy file](#working-with-uppy-files) that was added.
- ```js
- uppy.on('file-added', (file) => {
- console.log('Added file', file);
- });
- ```
- #### `files-added`
- **Parameters**
- - `files` - Array of [Uppy files](#working-with-uppy-files) which were added at
- once, in a batch.
- Fired each time when one or more files are added — one event, for all files
- #### `file-removed`
- Fired each time a file is removed.
- **Parameters**
- - `file` - The [Uppy file](#working-with-uppy-files) that was removed.
- - `reason` - A string explaining why the file was removed. See
- [#2301](https://github.com/transloadit/uppy/issues/2301#issue-628931176) for
- details. Current reasons are: `removed-by-user` and `cancel-all`.
- **Example**
- ```js
- uppy.on('file-removed', (file, reason) => {
- console.log('Removed file', file);
- });
- ```
- ```js
- uppy.on('file-removed', (file, reason) => {
- removeFileFromUploadingCounterUI(file);
- if (reason === 'removed-by-user') {
- sendDeleteRequestForFile(file);
- }
- });
- ```
- #### `upload`
- Fired when the upload starts.
- ```js
- uppy.on('upload', (data) => {
- // data object consists of `id` with upload ID and `fileIDs` array
- // with file IDs in current upload
- // data: { id, fileIDs }
- console.log(`Starting upload ${id} for files ${fileIDs}`);
- });
- ```
- #### `preprocess-progress`
- Progress of the pre-processors.
- **Parameters**
- `progress` is an object with properties:
- - `mode` - Either `'determinate'` or `'indeterminate'`.
- - `message` - A message to show to the user. Something like
- `'Preparing upload...'`, but be more specific if possible.
- When `mode` is `'determinate'`, also add the `value` property:
- - `value` - A progress value between 0 and 1.
- #### `progress`
- Fired each time the total upload progress is updated:
- **Parameters**
- - `progress` - An integer (0-100) representing the total upload progress.
- **Example**
- ```js
- uppy.on('progress', (progress) => {
- // progress: integer (total progress percentage)
- console.log(progress);
- });
- ```
- #### `upload-progress`
- Fired each time an individual file upload progress is available:
- **Parameters**
- - `file` - The [Uppy file](#working-with-uppy-files) that has progressed.
- - `progress` - The same object as in `file.progress`.
- **Example**
- ```js
- uppy.on('upload-progress', (file, progress) => {
- // file: { id, name, type, ... }
- // progress: { uploader, bytesUploaded, bytesTotal }
- console.log(file.id, progress.bytesUploaded, progress.bytesTotal);
- });
- ```
- #### `postprocess-progress`
- Progress of the post-processors.
- **Parameters**
- `progress` is an object with properties:
- - `mode` - Either `'determinate'` or `'indeterminate'`.
- - `message` - A message to show to the user. Something like
- `'Preparing upload...'`, but be more specific if possible.
- When `mode` is `'determinate'`, also add the `value` property:
- - `value` - A progress value between 0 and 1.
- #### `upload-success`
- Fired each time a single upload is completed.
- **Parameters**
- - `file` - The [Uppy file](#working-with-uppy-files) that was uploaded.
- - `response` - An object with response data from the remote endpoint. The actual
- contents depend on the upload plugin that is used.
- For `@uppy/xhr-upload`, the shape is:
- ```json
- {
- "status": 200, // HTTP status code (0, 200, 300)
- "body": "…", // response body
- "uploadURL": "…" // the file url, if it was returned
- }
- ```
- **Example**
- ```js
- uppy.on('upload-success', (file, response) => {
- console.log(file.name, response.uploadURL);
- const img = new Image();
- img.width = 300;
- img.alt = file.id;
- img.src = response.uploadURL;
- document.body.appendChild(img);
- });
- ```
- #### `complete`
- Fired when all uploads are complete.
- The `result` parameter is an object with arrays of `successful` and `failed`
- files, as in [`uppy.upload()`](#upload)’s return value.
- ```js
- uppy.on('complete', (result) => {
- console.log('successful files:', result.successful);
- console.log('failed files:', result.failed);
- });
- ```
- #### `error`
- Fired when Uppy fails to upload/encode the entire upload.
- **Parameters**
- - `error` - The error object.
- **Example**
- ```js
- uppy.on('error', (error) => {
- console.error(error.stack);
- });
- ```
- #### `upload-error`
- Fired each time a single upload failed.
- **Parameters**
- - `file` - The [Uppy file](#working-with-uppy-files) which didn’t upload.
- - `error` - The error object.
- - `response` - an optional parameter with response data from the upload
- endpoint.
- It may be undefined or contain different data depending on the upload plugin in
- use.
- For `@uppy/xhr-upload`, the shape is:
- ```json
- {
- "status": 200, // HTTP status code (0, 200, 300)
- "body": "…" // response body
- }
- ```
- **Example**
- ```js
- uppy.on('upload-error', (file, error, response) => {
- console.log('error with file:', file.id);
- console.log('error message:', error);
- });
- ```
- If the error is related to network conditions — endpoint unreachable due to
- firewall or ISP blockage, for instance — the error will have
- `error.isNetworkError` property set to `true`. Here’s how you can check for
- network errors:
- ```js
- uppy.on('upload-error', (file, error, response) => {
- if (error.isNetworkError) {
- // Let your users know that file upload could have failed
- // due to firewall or ISP issues
- alertUserAboutPossibleFirewallOrISPIssues(error);
- }
- });
- ```
- #### `upload-retry`
- Fired when an upload has been retried (after an error, for example).
- :::note
- This event is not triggered when the user retries all uploads, it will trigger
- the `retry-all` event instead.
- :::
- **Parameters**
- - `fileID` - ID of the file that is being retried.
- **Example**
- ```js
- uppy.on('upload-retry', (fileID) => {
- console.log('upload retried:', fileID);
- });
- ```
- #### `upload-stalled`
- Fired when an upload has not received any progress in some time (in
- `@uppy/xhr-upload`, the delay is defined by the `timeout` option). Use this
- event to display a message on the UI to tell the user they might want to retry
- the upload.
- ```js
- uppy.on('upload-stalled', (error, files) => {
- console.log('upload seems stalled', error, files);
- const noLongerStalledEventHandler = (file) => {
- if (files.includes(file)) {
- console.log('upload is no longer stalled');
- uppy.off('upload-progress', noLongerStalledEventHandler);
- }
- };
- uppy.on('upload-progress', noLongerStalledEventHandler);
- });
- ```
- #### `retry-all`
- Fired when all failed uploads are retried
- **Parameters**
- - `fileIDs` - Arrays of IDs of the files being retried.
- **Example**
- ```js
- uppy.on('retry-all', (fileIDs) => {
- console.log('upload retried:', fileIDs);
- });
- ```
- #### `info-visible`
- Fired when “info” message should be visible in the UI. By default, `Informer`
- plugin is displaying these messages (enabled by default in `Dashboard` plugin).
- You can use this event to show messages in your custom UI:
- ```js
- uppy.on('info-visible', () => {
- const { info } = uppy.getState();
- // info: {
- // isHidden: false,
- // type: 'error',
- // message: 'Failed to upload',
- // details: 'Error description'
- // }
- console.log(`${info.message} ${info.details}`);
- });
- ```
- #### `info-hidden`
- Fired when “info” message should be hidden in the UI. See
- [`info-visible`](#info-visible).
- #### `cancel-all`
- | Argument | Type | Description |
- | -------- | -------- | ----------------------------------- |
- | `reason` | `string` | See [uppy.cancelAll](####cancelAll) |
- Fired when `cancelAll()` is called, all uploads are canceled, files removed and
- progress is reset.
- #### `restriction-failed`
- Fired when a file violates certain restrictions when added. This event is
- providing another choice for those who want to customize the behavior of file
- upload restrictions.
- ```js
- uppy.on('restriction-failed', (file, error) => {
- // do some customized logic like showing system notice to users
- });
- ```
- #### `reset-progress`
- Fired when `resetProgress()` is called, each file has its upload progress reset
- to zero.
- ```js
- uppy.on('reset-progress', () => {
- // progress was reset
- });
- ```
- ## `new BasePlugin(uppy, options?)`
- The initial building block for a plugin.
- `BasePlugin` does not contain DOM rendering so it can be used for plugins
- without an user interface.
- :::info
- See [`UIPlugin`][] for the extended version with Preact rendering for
- interfaces.
- :::
- :::info
- Checkout the [building plugins](/docs/guides/building-plugins) guide.
- :::
- :::note
- If you don’t use any UI plugins and want to make sure Preact isn’t bundled into
- your app, import `BasePlugin` like this:
- `import BasePlugin from '@uppy/core/lib/BasePlugin`.
- :::
- ### Options
- The options passed to `BasePlugin` are all you options you wish to support in
- your plugin.
- You should pass the options to `super` in your plugin class:
- ```js
- class MyPlugin extends BasePlugin {
- constructor(uppy, opts) {
- super(uppy, opts);
- }
- }
- ```
- ### Methods
- #### `setOptions(options)`
- Options passed during initialization can also be altered dynamically with
- `setOptions`.
- #### `getPluginState()`
- Retrieves the plugin state from the `Uppy` class. Uppy keeps a `plugins` object
- in state in which each key is the plugin’s `id`, and the value its state.
- #### `setPluginState()`
- Set the plugin state in the `Uppy` class. Uppy keeps a `plugins` object in state
- in which each key is the plugin’s `id`, and the value its state.
- #### `install()`
- The `install` method is ran once, when the plugin is added to Uppy with
- `.use()`. Use this to initialize the plugin.
- For example, if you are creating a pre-processor (such as
- [@uppy/compressor](/docs/compressor)) you must add it:
- ```js
- install () {
- this.uppy.addPreProcessor(this.prepareUpload)
- }
- ```
- Another common thing to do when creating a
- [UI plugin](#new-uipluginuppy-options) is to [`mount`](#mounttarget) it to the
- DOM:
- ```js
- install () {
- const { target } = this.opts
- if (target) {
- this.mount(target, this)
- }
- }
- ```
- #### `uninstall()`
- The `uninstall` method is ran once, when the plugin is removed from Uppy. This
- happens when `.close()` is called or when the plugin is destroyed in a framework
- integration.
- Use this to clean things up.
- For instance when creating a pre-processor, uploader, or post-processor to
- remove it:
- ```js
- uninstall () {
- this.uppy.removePreProcessor(this.prepareUpload)
- }
- ```
- When creating a [UI plugin](#new-uipluginuppy-options) you should
- [`unmount`](#unmount) it from the DOM:
- ```js
- uninstall () {
- this.unmount()
- }
- ```
- #### `i18nInit`
- Call `this.i18nInit()` once in the constructor of your plugin class to
- initialize [internationalisation](/docs/locales).
- #### `addTarget`
- You can use this method to make your plugin a `target` for other plugins. This
- is what `@uppy/dashboard` uses to add other plugins to its UI.
- #### `update`
- Called on each state update. You will rarely need to use this, unless if you
- want to build a UI plugin using something other than Preact.
- #### `afterUpdate`
- Called after every state update with a debounce, after everything has mounted.
- ## `new UIPlugin(uppy, options?)`
- `UIPlugin` extends [`BasePlugin`][] to add rendering with
- [Preact](https://preactjs.com/). Use this when you want to create an user
- interface or an addition to one, such as [Dashboard][].
- :::info
- See [`BasePlugin`][] for the initial building block for all plugins.
- :::
- :::info
- Checkout the [building plugins](/docs/guides/building-plugins) guide.
- :::
- ### Options
- The options passed to `UIPlugin` are all you options you wish to support in your
- plugin.
- You should pass the options to `super` in your plugin class:
- ```js
- class MyPlugin extends UIPlugin {
- constructor(uppy, opts) {
- super(uppy, opts);
- }
- }
- ```
- In turn these are also passed to the underlying `BasePlugin`.
- ### Methods
- All the methods from [`BasePlugin`][] are also inherited into `UIPlugin`.
- #### `mount(target)`
- Mount this plugin to the `target` element. `target` can be a CSS query selector,
- a DOM element, or another Plugin. If `target` is a Plugin, the source (current)
- plugin will register with the target plugin, and the latter can decide how and
- where to render the source plugin.
- #### `onMount()`
- Called after Preact has rendered the components of the plugin.
- #### `unmount`
- Removing the plugin from the DOM. You generally don’t need to override it but
- you should call it from [`uninstall`](#uninstall).
- The default is:
- ```js
- unmount () {
- if (this.isTargetDOMEl) {
- this.el?.remove()
- }
- this.onUnmount()
- }
- ```
- #### `onUnmount()`
- Called after the elements have been removed from the DOM. Can be used to do some
- clean up or other side-effects.
- #### `render()`
- Render the UI of the plugin. Uppy uses [Preact](https://preactjs.com) as its
- view engine, so `render()` should return a Preact element. `render` is
- automatically called by Uppy on each state change.
- #### `update(state)`
- Called on each state update. You will rarely need to use this, unless if you
- want to build a UI plugin using something other than Preact.
- ## `debugLogger()`
- Logger with extra debug and warning logs for during development.
- ```js
- import { Uppy, debugLogger } from '@uppy/core';
- new Uppy({ logger: debugLogger });
- ```
- :::info
- You can also enable this logger by setting [`debug`](#debug) to `true`.
- :::
- The default value of [`logger`](#logger) is `justErrorsLogger`, which looks like
- this:
- ```js
- // Swallow all logs, except errors.
- // default if logger is not set or debug: false
- const justErrorsLogger = {
- debug: () => {},
- warn: () => {},
- error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
- };
- ```
- `debugLogger` sends extra debugging and warning logs which could be helpful
- during development:
- ```js
- // Print logs to console with namespace + timestamp,
- // set by logger: Uppy.debugLogger or debug: true
- const debugLogger = {
- debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
- warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
- error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
- };
- ```
- ## Frequently asked questions
- ### How do I allow duplicate files?
- You can allow all files, even duplicate files, with
- [`onBeforeFileAdded`](#onbeforefileadded). This will override the file if it has
- not been uploaded. If you upload a duplicate file again it depends on your
- upload plugin and backend how it is handled.
- ```js
- const uppy = new Uppy({
- // ...
- onBeforeFileAdded: () => true,
- ```
- [dashboard]: /docs/dashboard
- [`baseplugin`]: #new-basepluginuppy-options
- [`uiplugin`]: #new-uipluginuppy-options
|