uppy-core.mdx 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. ---
  2. sidebar_position: 3
  3. slug: /uppy
  4. ---
  5. import Tabs from '@theme/Tabs';
  6. import TabItem from '@theme/TabItem';
  7. import UppyCdnExample from '/src/components/UppyCdnExample';
  8. # Uppy core
  9. Uppy can be an uploader and an interface with a lot of features. Features can be
  10. added incrementally with plugins, but Uppy can be as bare bones as you want it
  11. to be. So we build Uppy’s heart, `@uppy/core`, as a standalone orchestrator. It
  12. acts as a state manager, event emitter, and restrictions handler.
  13. ## When should I use it?
  14. `@uppy/core` is the fundament of the Uppy ecosystem, the orchestrator for all
  15. added plugins. No matter the uploading experience you’re looking for, it all
  16. starts with installing this plugin.
  17. You can use `@uppy/core` and
  18. [build your own UI](/docs/guides/building-your-own-ui-with-uppy) or go for the
  19. [Dashboard](/docs/dashboard) integration. For an uploading plugin, you can refer
  20. to [choosing the uploader you need](/docs/guides/choosing-uploader).
  21. If you want to see how it all comes together, checkout the
  22. [examples](/examples).
  23. ## Install
  24. <Tabs>
  25. <TabItem value="npm" label="NPM" default>
  26. ```shell
  27. npm install @uppy/core
  28. ```
  29. </TabItem>
  30. <TabItem value="yarn" label="Yarn">
  31. ```shell
  32. yarn add @uppy/core
  33. ```
  34. </TabItem>
  35. <TabItem value="cdn" label="CDN">
  36. <UppyCdnExample>
  37. {`
  38. import { Uppy } from "{{UPPY_JS_URL}}"
  39. const uppy = new Uppy()
  40. `}
  41. </UppyCdnExample>
  42. </TabItem>
  43. </Tabs>
  44. ## Use
  45. `@uppy/core` has four exports: `Uppy`, `UIPlugin`, `BasePlugin`, and
  46. `debugLogger`. The default export is the `Uppy` class.
  47. ### Working with Uppy files
  48. Uppy keeps files in state with the [`File`][] browser API, but it’s wrapped in
  49. an `Object` to be able to add more data to it, which we call an _Uppy file_. All
  50. these properties can be useful for plugins and side-effects (such as
  51. [events](#events)).
  52. Mutating these properties should be done through [methods](#methods).
  53. <details>
  54. <summary>Uppy file properties</summary>
  55. #### `file.source`
  56. Name of the plugin that was responsible for adding this file. Typically a remote
  57. provider plugin like `'GoogleDrive'` or a UI plugin like `'DragDrop'`.
  58. #### `file.id`
  59. Unique ID for the file.
  60. #### `file.name`
  61. The name of the file.
  62. #### `file.meta`
  63. Object containing standard as well as user-defined metadata for each file. Any
  64. custom file metadata should be JSON-serializable. The following standard
  65. metadata will be stored on all file objects, but plugins may add more metadata.
  66. - `file.meta.name`
  67. - Same as `file.name`.
  68. - `file.meta.type`
  69. - Same as `file.type`.
  70. - `file.meta.relativePath`
  71. - For any local folder that was drag-dropped or opened in Uppy, the files
  72. inside the folder will have the `relativePath` metadata field set to their
  73. path, relative to the folder. `relativePath` begins with the folder’s name
  74. and ends with the file’s name. If opening or drag-dropping a file instead of
  75. a folder, `relativePath` will be `null`. The same behaviour exists for
  76. remote (provider) files, but the path will instead be relative to the user’s
  77. selection (checkboxes). No leading or trailing slashes.
  78. - **Local file example:** When drag-dropping a local folder `folder1` which
  79. has a folder inside of it named `folder2` which has a file named `file`
  80. inside of it, the `relativePath` meta field of the file will be
  81. `folder1/folder2/file`. However if drag-dropping or opening `file` directly,
  82. `relativePath` will be `null`.
  83. - **Remote file example:** Suppose we have a remote provider folder structure
  84. such as `/folder1/folder2/file`. Then, if the user checks the checkbox next
  85. to `folder1`, `file`’s `relativePath` will be `"folder1/folder2/file"`.
  86. However if the user first navigates into `folder1`, and only then checks the
  87. checkbox next to `folder2`, `relativePath` will be `"folder2/file"`.
  88. - `file.meta.absolutePath`
  89. - The `absolutePath` meta field will only be set for remote files. Regardless
  90. of user selection, it will always be the path relative to the root of the
  91. provider’s list of files, as presented to the user. `absolutePath` always
  92. begins with a `/` and will always end with the file’s name. To clarify: The
  93. difference between `absolutePath` and `relativePath` is that `absolutePath`
  94. only exists for remote files, and always has the full path to the file,
  95. while `relativePath` is the file’s path _relative to the user’s selected
  96. folder_.
  97. #### `file.type`
  98. MIME type of the file. This may actually be guessed if a file type was not
  99. provided by the user’s browser, so this is a best-effort value and not
  100. guaranteed to be correct.
  101. #### `file.data`
  102. For local files, this is the actual [`File`][] or [`Blob`][] object representing
  103. the file contents.
  104. For files that are imported from remote providers, the file data is not
  105. available in the browser.
  106. [`file`]: https://developer.mozilla.org/en-US/docs/Web/API/File
  107. [`blob`]: https://developer.mozilla.org/en-US/docs/Web/API/Blob
  108. #### `file.progress`
  109. An object with upload progress data.
  110. **Properties**
  111. - `bytesUploaded` - Number of bytes uploaded so far.
  112. - `bytesTotal` - Number of bytes that must be uploaded in total.
  113. - `uploadStarted` - Null if the upload has not started yet. Once started, this
  114. property stores a UNIX timestamp. Note that this is only set _after_
  115. preprocessing.
  116. - `uploadComplete` - Boolean indicating if the upload has completed. Note this
  117. does _not_ mean that postprocessing has completed, too.
  118. - `percentage` - Integer percentage between 0 and 100.
  119. #### `file.size`
  120. Size in bytes of the file.
  121. #### `file.isRemote`
  122. Boolean: is this file imported from a remote provider?
  123. #### `file.remote`
  124. Grab bag of data for remote providers. Generally not interesting for end users.
  125. #### `file.preview`
  126. An optional URL to a visual thumbnail for the file.
  127. #### `file.uploadURL`
  128. When an upload is completed, this may contain a URL to the uploaded file.
  129. Depending on server configuration it may not be accessible or correct.
  130. </details>
  131. ## `new Uppy(options?)`
  132. ```js
  133. import Uppy from '@uppy/core';
  134. const uppy = new Uppy();
  135. ```
  136. ### Options
  137. #### `id`
  138. A site-wide unique ID for the instance (`string`, default: `uppy`).
  139. :::note
  140. If several Uppy instances are being used, for instance, on two different pages,
  141. an `id` should be specified. This allows Uppy to store information in
  142. `localStorage` without colliding with other Uppy instances.
  143. This ID should be persistent across page reloads and navigation—it shouldn’t be
  144. a random number that is different every time Uppy is loaded.
  145. :::
  146. #### `autoProceed`
  147. Upload as soon as files are added (`boolean`, default: `false`).
  148. By default Uppy will wait for an upload button to be pressed in the UI, or the
  149. `.upload()` method to be called before starting an upload. Setting this to
  150. `true` will start uploading automatically after the first file is selected
  151. #### `allowMultipleUploadBatches`
  152. Whether to allow several upload batches (`boolean`, default: `true`).
  153. This means several calls to `.upload()`, or a user adding more files after
  154. already uploading some. An upload batch is made up of the files that were added
  155. since the earlier `.upload()` call.
  156. With this option set to `true`, users can upload some files, and then add _more_
  157. files and upload those as well. A model use case for this is uploading images to
  158. a gallery or adding attachments to an email.
  159. With this option set to `false`, users can upload some files, and you can listen
  160. for the [`'complete'`](#complete) event to continue to the next step in your
  161. app’s upload flow. A typical use case for this is uploading a new profile
  162. picture. If you are integrating with an existing HTML form, this option gives
  163. the closest behaviour to a bare `<input type="file">`.
  164. #### `debug`
  165. Whether to send debugging and warning logs (`boolean`, default: `false`).
  166. Setting this to `true` sets the [`logger`](#logger) to
  167. [`debugLogger`](#debuglogger).
  168. #### `logger`
  169. Logger used for [`uppy.log`](#logmessage-type) (`Object`, default:
  170. `justErrorsLogger`).
  171. By providing your own `logger`, you can send the debug information to a server,
  172. choose to log errors only, etc.
  173. :::note
  174. Set `logger` to [`debugLogger`](#debuglogger) to get debug info output to the
  175. browser console:
  176. :::
  177. :::note
  178. You can also provide your own logger object: it should expose `debug`, `warn`
  179. and `error` methods, as shown in the examples below.
  180. Here’s an example of a `logger` that does nothing:
  181. ```js
  182. const nullLogger = {
  183. debug: (...args) => {},
  184. warn: (...args) => {},
  185. error: (...args) => {},
  186. };
  187. ```
  188. :::
  189. #### `restrictions`
  190. Conditions for restricting an upload (`Object`, default: `{}`).
  191. | Property | Value | Description |
  192. | -------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
  193. | `maxFileSize` | `number` | maximum file size in bytes for each individual file |
  194. | `minFileSize` | `number` | minimum file size in bytes for each individual file |
  195. | `maxTotalFileSize` | `number` | maximum file size in bytes for all the files that can be selected for upload |
  196. | `maxNumberOfFiles` | `number` | total number of files that can be selected |
  197. | `minNumberOfFiles` | `number` | minimum number of files that must be selected before the upload |
  198. | `allowedFileTypes` | `Array` | wildcards `image/*`, or exact mime types `image/jpeg`, or file extensions `.jpg`: `['image/*', '.jpg', '.jpeg', '.png', '.gif']` |
  199. | `requiredMetaFields` | `Array<string>` | make keys from the `meta` object in every file required before uploading |
  200. :::note
  201. `maxNumberOfFiles` also affects the number of files a user is able to select via
  202. the system file dialog in UI plugins like `DragDrop`, `FileInput` and
  203. `Dashboard`. When set to `1`, they will only be able to select a single file.
  204. When `null` or another number is provided, they will be able to select several
  205. files.
  206. :::
  207. :::note
  208. `allowedFileTypes` gets passed to the file system dialog via the
  209. [`<input>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#Limiting_accepted_file_types)
  210. accept attribute, so only types supported by the browser will work.
  211. :::
  212. :::tip
  213. If you’d like to force a certain meta field data to be entered before the
  214. upload, you can
  215. [do so using `onBeforeUpload`](https://github.com/transloadit/uppy/issues/1703#issuecomment-507202561).
  216. :::
  217. :::tip
  218. If you need to restrict `allowedFileTypes` to a file extension with double dots,
  219. like `.nii.gz`, you can do so by
  220. [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).
  221. :::
  222. #### `meta`
  223. Key/value pairs to add to each file’s `metadata` (`Object`, default: `{}`).
  224. :::note
  225. Metadata from each file is then attached to uploads in the [Tus](/docs/tus) and
  226. [XHR](/docs/xhr-upload) plugins.
  227. :::
  228. :::info
  229. Two methods also exist for updating `metadata`: [`setMeta`](#setmetadata) and
  230. [`setFileMeta`](#setfilemetafileid-data).
  231. :::
  232. :::info
  233. Metadata can also be added from a `<form>` element on your page, through the
  234. [Form](#) plugin or through the UI if you are using Dashboard with the
  235. [`metaFields`](/docs/dashboard#metafields) option.
  236. :::
  237. <i id="onBeforeFileAdded" />
  238. #### `onBeforeFileAdded(file, files)`
  239. A function called before a file is added to Uppy (`Function`, default:
  240. `(files, file) => !Object.hasOwn(files, file.id)`).
  241. Use this function to run any number of custom checks on the selected file, or
  242. manipulate it, for instance, by optimizing a file name. You can also allow
  243. duplicate files with this.
  244. You can return `true` to keep the file as is, `false` to remove the file, or
  245. return a modified file.
  246. :::caution
  247. This method is intended for quick synchronous checks and modifications only. If
  248. you need to do an async API call, or heavy work on a file (like compression or
  249. encryption), you should use a [custom plugin](/docs/guides/building-plugins)
  250. instead.
  251. :::
  252. :::info
  253. No notification will be shown to the user about a file not passing validation by
  254. default. We recommend showing a message using
  255. [`uppy.info()`](#infomessage-type-duration) and logging to console for debugging
  256. purposes via [`uppy.log()`](#logmessage-type).
  257. :::
  258. <details>
  259. <summary>Filter, change, and abort example</summary>
  260. Allow all files, also duplicate files. This will replace the file if it has not
  261. been uploaded. If you upload a duplicate file again it depends on your upload
  262. plugin and backend how it is handled.
  263. ```js
  264. const uppy = new Uppy({
  265. // ...
  266. onBeforeFileAdded: () => true,
  267. ```
  268. Keep only files under a condition:
  269. ```js
  270. const uppy = new Uppy({
  271. // ...
  272. onBeforeFileAdded: (currentFile, files) => {
  273. if (currentFile.name === 'forest-IMG_0616.jpg') {
  274. return true
  275. }
  276. return false
  277. },
  278. ```
  279. Change all file names:
  280. ```js
  281. const uppy = new Uppy({
  282. // ...
  283. onBeforeFileAdded: (currentFile, files) => {
  284. const modifiedFile = {
  285. ...currentFile,
  286. name: `${currentFile.name}__${Date.now()}`,
  287. }
  288. return modifiedFile
  289. },
  290. ```
  291. Abort a file:
  292. ```js
  293. const uppy = new Uppy({
  294. // ...
  295. onBeforeFileAdded: (currentFile, files) => {
  296. if (!currentFile.type) {
  297. // log to console
  298. uppy.log(`Skipping file because it has no type`);
  299. // show error message to the user
  300. uppy.info(`Skipping file because it has no type`, 'error', 500);
  301. return false;
  302. }
  303. },
  304. });
  305. ```
  306. </details>
  307. #### `onBeforeUpload(files)`
  308. A function called before when upload is initiated (`Function`, default:
  309. `(files) => files`).
  310. Use this to check if all files or their total number match your requirements, or
  311. manipulate all the files at once before upload.
  312. You can return `true` to continue the upload, `false` to cancel it, or return
  313. modified files.
  314. :::caution
  315. This method is intended for quick synchronous checks and modifications only. If
  316. you need to do an async API call, or heavy work on a file (like compression or
  317. encryption), you should use a [custom plugin](/docs/guides/building-plugins)
  318. instead.
  319. :::
  320. :::info
  321. No notification will be shown to the user about a file not passing validation by
  322. default. We recommend showing a message using
  323. [`uppy.info()`](#infomessage-type-duration) and logging to console for debugging
  324. purposes via [`uppy.log()`](#logmessage-type).
  325. :::
  326. <details>
  327. <summary>Change and abort example</summary>
  328. Change all file names:
  329. ```js
  330. const uppy = new Uppy({
  331. // ...
  332. onBeforeUpload: (files) => {
  333. // We’ll be careful to return a new object, not mutating the original `files`
  334. const updatedFiles = {};
  335. Object.keys(files).forEach((fileID) => {
  336. updatedFiles[fileID] = {
  337. ...files[fileID],
  338. name: `${myCustomPrefix}__${files[fileID].name}`,
  339. };
  340. });
  341. return updatedFiles;
  342. },
  343. });
  344. ```
  345. Abort an upload:
  346. ```js
  347. const uppy = new Uppy({
  348. // ...
  349. onBeforeUpload: (files) => {
  350. if (Object.keys(files).length < 2) {
  351. // log to console
  352. uppy.log(
  353. `Aborting upload because only ${
  354. Object.keys(files).length
  355. } files were selected`,
  356. );
  357. // show error message to the user
  358. uppy.info(`You have to select at least 2 files`, 'error', 500);
  359. return false;
  360. }
  361. return true;
  362. },
  363. });
  364. ```
  365. </details>
  366. #### `locale`
  367. You can override locale strings by passing the `strings` object with the keys
  368. you want to override.
  369. :::note
  370. Array indexed objects are used for pluralisation.
  371. :::
  372. :::info
  373. If you want a different language it’s better to use [locales](/docs/locales).
  374. :::
  375. ```js
  376. module.exports = {
  377. strings: {
  378. addBulkFilesFailed: {
  379. 0: 'Failed to add %{smart_count} file due to an internal error',
  380. 1: 'Failed to add %{smart_count} files due to internal errors',
  381. },
  382. youCanOnlyUploadX: {
  383. 0: 'You can only upload %{smart_count} file',
  384. 1: 'You can only upload %{smart_count} files',
  385. },
  386. youHaveToAtLeastSelectX: {
  387. 0: 'You have to select at least %{smart_count} file',
  388. 1: 'You have to select at least %{smart_count} files',
  389. },
  390. exceedsSize: '%{file} exceeds maximum allowed size of %{size}',
  391. missingRequiredMetaField: 'Missing required meta fields',
  392. missingRequiredMetaFieldOnFile:
  393. 'Missing required meta fields in %{fileName}',
  394. inferiorSize: 'This file is smaller than the allowed size of %{size}',
  395. youCanOnlyUploadFileTypes: 'You can only upload: %{types}',
  396. noMoreFilesAllowed: 'Cannot add more files',
  397. noDuplicates:
  398. "Cannot add the duplicate file '%{fileName}', it already exists",
  399. companionError: 'Connection with Companion failed',
  400. authAborted: 'Authentication aborted',
  401. companionUnauthorizeHint:
  402. 'To unauthorize to your %{provider} account, please go to %{url}',
  403. failedToUpload: 'Failed to upload %{file}',
  404. noInternetConnection: 'No Internet connection',
  405. connectedToInternet: 'Connected to the Internet',
  406. // Strings for remote providers
  407. noFilesFound: 'You have no files or folders here',
  408. selectX: {
  409. 0: 'Select %{smart_count}',
  410. 1: 'Select %{smart_count}',
  411. },
  412. allFilesFromFolderNamed: 'All files from folder %{name}',
  413. openFolderNamed: 'Open folder %{name}',
  414. cancel: 'Cancel',
  415. logOut: 'Log out',
  416. filter: 'Filter',
  417. resetFilter: 'Reset filter',
  418. loading: 'Loading...',
  419. authenticateWithTitle:
  420. 'Please authenticate with %{pluginName} to select files',
  421. authenticateWith: 'Connect to %{pluginName}',
  422. signInWithGoogle: 'Sign in with Google',
  423. searchImages: 'Search for images',
  424. enterTextToSearch: 'Enter text to search for images',
  425. search: 'Search',
  426. emptyFolderAdded: 'No files were added from empty folder',
  427. folderAlreadyAdded: 'The folder "%{folder}" was already added',
  428. folderAdded: {
  429. 0: 'Added %{smart_count} file from %{folder}',
  430. 1: 'Added %{smart_count} files from %{folder}',
  431. },
  432. },
  433. };
  434. ```
  435. #### `store`
  436. The store that is used to keep track of internal state (`Object`, default:
  437. [`DefaultStore`](/docs/guides/custom-stores)).
  438. This option can be used to plug Uppy state into an external state management
  439. library, such as [Redux](/docs/guides/custom-stores).
  440. {/* TODO document store API */}
  441. #### `infoTimeout`
  442. How long an [Informer](/docs/informer) notification will be visible (`number`,
  443. default: `5000`).
  444. ### Methods
  445. #### `use(plugin, opts)`
  446. Add a plugin to Uppy, with an optional plugin options object.
  447. ```js
  448. import Uppy from '@uppy/core';
  449. import DragDrop from '@uppy/drag-drop';
  450. const uppy = new Uppy();
  451. uppy.use(DragDrop, { target: 'body' });
  452. ```
  453. #### `removePlugin(instance)`
  454. Uninstall and remove a plugin.
  455. #### `getPlugin(id)`
  456. Get a plugin by its `id` to access its methods.
  457. #### `getID()`
  458. Get the Uppy instance ID, see the [`id`](#id) option.
  459. #### `addFile(file)`
  460. Add a new file to Uppy’s internal state. `addFile` will return the generated id
  461. for the file that was added.
  462. `addFile` gives an error if the file cannot be added, either because
  463. `onBeforeFileAdded(file)` gave an error, or because `uppy.opts.restrictions`
  464. checks failed.
  465. ```js
  466. uppy.addFile({
  467. name: 'my-file.jpg', // file name
  468. type: 'image/jpeg', // file type
  469. data: blob, // file blob
  470. meta: {
  471. // optional, store the directory path of a file so Uppy can tell identical files in different directories apart.
  472. relativePath: webkitFileSystemEntry.relativePath,
  473. },
  474. source: 'Local', // optional, determines the source of the file, for example, Instagram.
  475. isRemote: false, // optional, set to true if actual file is not in the browser, but on some remote server, for example,
  476. // when using companion in combination with Instagram.
  477. });
  478. ```
  479. :::note
  480. If you try to add a file that already exists, `addFile` will throw an error.
  481. Unless that duplicate file was dropped with a folder — duplicate files from
  482. different folders are allowed, when selected with that folder. This is because
  483. we add `file.meta.relativePath` to the `file.id`.
  484. :::
  485. :::info
  486. Checkout [working with Uppy files](#working-with-uppy-files).
  487. :::
  488. :::info
  489. If `uppy.opts.autoProceed === true`, Uppy will begin uploading automatically
  490. when files are added.
  491. :::
  492. :::info
  493. Sometimes you might need to add a remote file to Uppy. This can be achieved by
  494. [fetching the file, then creating a Blob object, or using the Url plugin with Companion](https://github.com/transloadit/uppy/issues/1006#issuecomment-413495493).
  495. :::
  496. :::info
  497. Sometimes you might need to mark some files as “already uploaded”, so that the
  498. user sees them, but they won’t actually be uploaded by Uppy. This can be
  499. achieved by
  500. [looping through files and setting `uploadComplete: true, uploadStarted: true` on them](https://github.com/transloadit/uppy/issues/1112#issuecomment-432339569)
  501. :::
  502. #### `removeFile(fileID)`
  503. Remove a file from Uppy. Removing a file that is already being uploaded cancels
  504. that upload.
  505. ```js
  506. uppy.removeFile('uppyteamkongjpg1501851828779');
  507. ```
  508. #### `clear()`
  509. Clear the state. Can be useful for manually resetting Uppy after a successful
  510. upload.
  511. Upload plugins may choose to throw an error if called during an upload.
  512. #### `getFile(fileID)`
  513. Get a specific [Uppy file](#working-with-uppy-files) by its ID.
  514. ```js
  515. const file = uppy.getFile('uppyteamkongjpg1501851828779');
  516. ```
  517. #### `getFiles()`
  518. Get an array of all added [Uppy files](#working-with-uppy-files).
  519. ```js
  520. const files = uppy.getFiles();
  521. ```
  522. #### `upload()`
  523. Start uploading added files.
  524. Returns a Promise `result` that resolves with an object containing two arrays of
  525. uploaded files:
  526. - `result.successful` - Files that were uploaded successfully.
  527. - `result.failed` - Files that did not upload successfully. These files will
  528. have a `.error` property describing what went wrong.
  529. ```js
  530. uppy.upload().then((result) => {
  531. console.info('Successful uploads:', result.successful);
  532. if (result.failed.length > 0) {
  533. console.error('Errors:');
  534. result.failed.forEach((file) => {
  535. console.error(file.error);
  536. });
  537. }
  538. });
  539. ```
  540. #### `pauseResume(fileID)`
  541. Toggle pause/resume on an upload. Will only work if resumable upload plugin,
  542. such as [Tus](/docs/tus/), is used.
  543. #### `pauseAll()`
  544. Pause all uploads. Will only work if a resumable upload plugin, such as
  545. [Tus](/docs/tus/), is used.
  546. #### `resumeAll()`
  547. Resume all uploads. Will only work if resumable upload plugin, such as
  548. [Tus](/docs/tus/), is used.
  549. #### `retryUpload(fileID)`
  550. Retry an upload (after an error, for example).
  551. #### `retryAll()`
  552. Retry all uploads (after an error, for example).
  553. #### `cancelAll()`
  554. Cancel all uploads, reset progress and remove all files.
  555. #### `setState(patch)`
  556. Update Uppy’s internal state. Usually, this method is called internally, but in
  557. some cases it might be useful to alter something directly, especially when
  558. implementing your own plugins.
  559. Uppy’s default state on initialization:
  560. ```js
  561. const state = {
  562. plugins: {},
  563. files: {},
  564. currentUploads: {},
  565. capabilities: {
  566. resumableUploads: false,
  567. },
  568. totalProgress: 0,
  569. meta: { ...this.opts.meta },
  570. info: {
  571. isHidden: true,
  572. type: 'info',
  573. message: '',
  574. },
  575. };
  576. ```
  577. Updating state:
  578. ```js
  579. uppy.setState({ smth: true });
  580. ```
  581. :::note
  582. State in Uppy is considered to be immutable. When updating values, make sure not
  583. mutate them, but instead create copies. See
  584. [Redux docs](http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html)
  585. for more info on this.
  586. :::
  587. #### `getState()`
  588. Returns the current state from the [Store](#store).
  589. #### `setFileState(fileID, state)`
  590. Update the state for a single file. This is mostly useful for plugins that may
  591. want to store data on [Uppy files](#working-with-uppy-files), or need to pass
  592. file-specific configurations to other plugins that support it.
  593. `fileID` is the string file ID. `state` is an object that will be merged into
  594. the file’s state object.
  595. #### `setMeta(data)`
  596. Alters global `meta` object in state, the one that can be set in Uppy options
  597. and gets merged with all newly added files. Calling `setMeta` will also merge
  598. newly added meta data with files that had been selected before.
  599. ```js
  600. uppy.setMeta({ resize: 1500, token: 'ab5kjfg' });
  601. ```
  602. #### `setFileMeta(fileID, data)`
  603. Update metadata for a specific file.
  604. ```js
  605. uppy.setFileMeta('myfileID', { resize: 1500 });
  606. ```
  607. #### `setOptions(opts)`
  608. Change the options Uppy initialized with.
  609. ```js
  610. const uppy = new Uppy();
  611. uppy.setOptions({
  612. restrictions: { maxNumberOfFiles: 3 },
  613. autoProceed: true,
  614. });
  615. uppy.setOptions({
  616. locale: {
  617. strings: {
  618. cancel: 'Отмена',
  619. },
  620. },
  621. });
  622. ```
  623. You can also change options for plugin:
  624. ```js
  625. // Change width of the Dashboard drag-and-drop aread on the fly
  626. uppy.getPlugin('Dashboard').setOptions({
  627. width: 300,
  628. });
  629. ```
  630. #### `destroy()`
  631. Uninstall all plugins and close down this Uppy instance. Also runs
  632. `uppy.cancelAll()` before uninstalling.
  633. #### `logout()`
  634. Calls `provider.logout()` on each remote provider plugin (Google Drive,
  635. Instagram, etc). Useful, for example, after your users log out of their account
  636. in your app — this will clean things up with Uppy cloud providers as well, for
  637. extra security.
  638. #### `log(message, type)`
  639. | Argument | Type | Description |
  640. | --------- | --------- | --------------------------- |
  641. | `message` | `string` | message to log |
  642. | `type` | `string?` | `debug`, `warn`, or `error` |
  643. See [`logger`](#logger) docs for details.
  644. ```js
  645. uppy.log('[Dashboard] adding files...');
  646. ```
  647. #### `info(message, type, duration)`
  648. Sets a message in state, with optional details, that can be shown by
  649. notification UI plugins. It’s using the [Informer](/docs/informer) plugin,
  650. included by default in Dashboard.
  651. | Argument | Type | Description |
  652. | ---------- | ------------------ | --------------------------------------------------------------------------------- |
  653. | `message` | `string`, `Object` | `'info message'` or `{ message: 'Oh no!', details: 'File couldn’t be uploaded' }` |
  654. | `type` | `string?` | `'info'`, `'warning'`, `'success'` or `'error'` |
  655. | `duration` | `number?` | in milliseconds |
  656. `info-visible` and `info-hidden` events are emitted when this info message
  657. should be visible or hidden.
  658. ```js
  659. this.info('Oh my, something good happened!', 'success', 3000);
  660. ```
  661. ```js
  662. this.info(
  663. {
  664. message: 'Oh no, something bad happened!',
  665. details:
  666. 'File couldn’t be uploaded because there is no internet connection',
  667. },
  668. 'error',
  669. 5000,
  670. );
  671. ```
  672. #### `addPreProcessor(fn)`
  673. Add a preprocessing function. `fn` gets called with a list of file IDs before an
  674. upload starts. `fn` should return a Promise. Its resolution value is ignored.
  675. :::info
  676. To change file data and such, use Uppy state updates, for example using
  677. [`setFileState`](#setfilestatefileid-state).
  678. :::
  679. #### `addUploader(fn)`
  680. Add an uploader function. `fn` gets called with a list of file IDs when an
  681. upload should start. Uploader functions should do the actual uploading work,
  682. such as creating and sending an XMLHttpRequest or calling into some upload
  683. service SDK. `fn` should return a Promise that resolves once all files have been
  684. uploaded.
  685. :::tip
  686. You may choose to still resolve the Promise if some file uploads fail. This way,
  687. any postprocessing will still run on the files that were uploaded successfully,
  688. while uploads that failed will be retried when [`retryAll`](#retryall) is
  689. called.
  690. :::
  691. #### `addPostProcessor(fn)`
  692. Add a postprocessing function. `fn` is called with a list of file IDs when an
  693. upload has finished. `fn` should return a Promise that resolves when the
  694. processing work is complete. The value of the Promise is ignored.
  695. For example, you could wait for file encoding or CDN propagation to complete, or
  696. you could do an HTTP API call to create an album containing all images that were
  697. uploaded.
  698. #### `removePreProcessor/removeUploader/removePostProcessor(fn)`
  699. Remove a processor or uploader function that was added before. Normally, this
  700. should be done in the [`uninstall()`](#uninstall) method.
  701. #### `on('event', action)`
  702. Subscribe to an uppy-event. See below for the full list of events.
  703. #### `once('event', action)`
  704. Create an event listener that fires once. See below for the full list of events.
  705. #### `off('event', action)`
  706. Unsubscribe to an uppy-event. See below for the full list of events.
  707. ### Events
  708. Uppy exposes events that you can subscribe to for side-effects.
  709. #### `file-added`
  710. Fired each time a file is added.
  711. **Parameters**
  712. - `file` - The [Uppy file](#working-with-uppy-files) that was added.
  713. ```js
  714. uppy.on('file-added', (file) => {
  715. console.log('Added file', file);
  716. });
  717. ```
  718. #### `files-added`
  719. **Parameters**
  720. - `files` - Array of [Uppy files](#working-with-uppy-files) which were added at
  721. once, in a batch.
  722. Fired each time when one or more files are added — one event, for all files
  723. #### `file-removed`
  724. Fired each time a file is removed.
  725. **Parameters**
  726. - `file` - The [Uppy file](#working-with-uppy-files) that was removed.
  727. **Example**
  728. ```js
  729. uppy.on('file-removed', (file) => {
  730. console.log('Removed file', file);
  731. });
  732. ```
  733. ```js
  734. uppy.on('file-removed', (file) => {
  735. removeFileFromUploadingCounterUI(file);
  736. sendDeleteRequestForFile(file);
  737. });
  738. ```
  739. #### `upload`
  740. Fired when the upload starts.
  741. **Parameters**
  742. - `uploadID` (`string)`
  743. - `files` (`UppyFile<M,B>`)
  744. #### `preprocess-progress`
  745. Progress of the pre-processors.
  746. **Parameters**
  747. `progress` is an object with properties:
  748. - `mode` - Either `'determinate'` or `'indeterminate'`.
  749. - `message` - A message to show to the user. Something like
  750. `'Preparing upload...'`, but be more specific if possible.
  751. When `mode` is `'determinate'`, also add the `value` property:
  752. - `value` - A progress value between 0 and 1.
  753. #### `progress`
  754. Fired each time the total upload progress is updated:
  755. **Parameters**
  756. - `progress` - An integer (0-100) representing the total upload progress.
  757. **Example**
  758. ```js
  759. uppy.on('progress', (progress) => {
  760. // progress: integer (total progress percentage)
  761. console.log(progress);
  762. });
  763. ```
  764. #### `upload-progress`
  765. Fired each time an individual file upload progress is available:
  766. **Parameters**
  767. - `file` - The [Uppy file](#working-with-uppy-files) that has progressed.
  768. - `progress` - The same object as in `file.progress`.
  769. **Example**
  770. ```js
  771. uppy.on('upload-progress', (file, progress) => {
  772. // file: { id, name, type, ... }
  773. // progress: { uploader, bytesUploaded, bytesTotal }
  774. console.log(file.id, progress.bytesUploaded, progress.bytesTotal);
  775. });
  776. ```
  777. #### `upload-pause`
  778. Fired when an individual upload is (un)paused.
  779. **Parameters**
  780. - `file` (`UppyFile<M,B>`)
  781. - `isPaused` (`boolean`)
  782. #### `postprocess-progress`
  783. Progress of the post-processors.
  784. **Parameters**
  785. `progress` is an object with properties:
  786. - `mode` - Either `'determinate'` or `'indeterminate'`.
  787. - `message` - A message to show to the user. Something like
  788. `'Preparing upload...'`, but be more specific if possible.
  789. When `mode` is `'determinate'`, also add the `value` property:
  790. - `value` - A progress value between 0 and 1.
  791. #### `upload-success`
  792. Fired each time a single upload is completed.
  793. **Parameters**
  794. - `file` - The [Uppy file](#working-with-uppy-files) that was uploaded.
  795. - `response` - An object with response data from the remote endpoint. The actual
  796. contents depend on the upload plugin that is used.
  797. For `@uppy/xhr-upload`, the shape is:
  798. ```json
  799. {
  800. "status": 200, // HTTP status code (0, 200, 300)
  801. "body": "…", // response body
  802. "uploadURL": "…" // the file url, if it was returned
  803. }
  804. ```
  805. **Example**
  806. ```js
  807. uppy.on('upload-success', (file, response) => {
  808. console.log(file.name, response.uploadURL);
  809. const img = new Image();
  810. img.width = 300;
  811. img.alt = file.id;
  812. img.src = response.uploadURL;
  813. document.body.appendChild(img);
  814. });
  815. ```
  816. #### `complete`
  817. Fired when all uploads are complete.
  818. The `result` parameter is an object with arrays of `successful` and `failed`
  819. files, as in [`uppy.upload()`](#upload)’s return value.
  820. ```js
  821. uppy.on('complete', (result) => {
  822. console.log('successful files:', result.successful);
  823. console.log('failed files:', result.failed);
  824. });
  825. ```
  826. #### `error`
  827. Fired when Uppy fails to upload/encode the entire upload.
  828. **Parameters**
  829. - `error` - The error object.
  830. **Example**
  831. ```js
  832. uppy.on('error', (error) => {
  833. console.error(error.stack);
  834. });
  835. ```
  836. #### `upload-error`
  837. Fired each time a single upload failed.
  838. **Parameters**
  839. - `file` - The [Uppy file](#working-with-uppy-files) which didn’t upload.
  840. - `error` - The error object.
  841. - `response` - an optional parameter with response data from the upload
  842. endpoint.
  843. It may be undefined or contain different data depending on the upload plugin in
  844. use.
  845. For `@uppy/xhr-upload`, the shape is:
  846. ```json
  847. {
  848. "status": 200, // HTTP status code (0, 200, 300)
  849. "body": "…" // response body
  850. }
  851. ```
  852. **Example**
  853. ```js
  854. uppy.on('upload-error', (file, error, response) => {
  855. console.log('error with file:', file.id);
  856. console.log('error message:', error);
  857. });
  858. ```
  859. If the error is related to network conditions — endpoint unreachable due to
  860. firewall or ISP blockage, for instance — the error will have
  861. `error.isNetworkError` property set to `true`. Here’s how you can check for
  862. network errors:
  863. ```js
  864. uppy.on('upload-error', (file, error, response) => {
  865. if (error.isNetworkError) {
  866. // Let your users know that file upload could have failed
  867. // due to firewall or ISP issues
  868. alertUserAboutPossibleFirewallOrISPIssues(error);
  869. }
  870. });
  871. ```
  872. #### `upload-retry`
  873. Fired when an upload has been retried (after an error, for example).
  874. :::note
  875. This event is not triggered when the user retries all uploads, it will trigger
  876. the `retry-all` event instead.
  877. :::
  878. **Parameters**
  879. - `file` (`UppyFile<M,B>`)
  880. **Example**
  881. ```js
  882. uppy.on('upload-retry', (fileID) => {
  883. console.log('upload retried:', fileID);
  884. });
  885. ```
  886. #### `upload-stalled`
  887. Fired when an upload has not received any progress in some time (in
  888. `@uppy/xhr-upload`, the delay is defined by the `timeout` option). Use this
  889. event to display a message on the UI to tell the user they might want to retry
  890. the upload.
  891. ```js
  892. uppy.on('upload-stalled', (error, files) => {
  893. console.log('upload seems stalled', error, files);
  894. const noLongerStalledEventHandler = (file) => {
  895. if (files.includes(file)) {
  896. console.log('upload is no longer stalled');
  897. uppy.off('upload-progress', noLongerStalledEventHandler);
  898. }
  899. };
  900. uppy.on('upload-progress', noLongerStalledEventHandler);
  901. });
  902. ```
  903. #### `retry-all`
  904. Fired when all failed uploads are retried
  905. **Parameters**
  906. - `files` (`UppyFile<M,B>[]`)
  907. **Example**
  908. ```js
  909. uppy.on('retry-all', (fileIDs) => {
  910. console.log('upload retried:', fileIDs);
  911. });
  912. ```
  913. #### `info-visible`
  914. Fired when “info” message should be visible in the UI. By default, `Informer`
  915. plugin is displaying these messages (enabled by default in `Dashboard` plugin).
  916. You can use this event to show messages in your custom UI:
  917. ```js
  918. uppy.on('info-visible', () => {
  919. const { info } = uppy.getState();
  920. // info: {
  921. // isHidden: false,
  922. // type: 'error',
  923. // message: 'Failed to upload',
  924. // details: 'Error description'
  925. // }
  926. console.log(`${info.message} ${info.details}`);
  927. });
  928. ```
  929. #### `info-hidden`
  930. Fired when “info” message should be hidden in the UI. See
  931. [`info-visible`](#info-visible).
  932. #### `cancel-all`
  933. Fired when `cancelAll()` is called, all uploads are canceled, files removed and
  934. progress is reset.
  935. #### `restriction-failed`
  936. Fired when a file violates certain restrictions when added. This event is
  937. providing another choice for those who want to customize the behavior of file
  938. upload restrictions.
  939. ```js
  940. uppy.on('restriction-failed', (file, error) => {
  941. // do some customized logic like showing system notice to users
  942. });
  943. ```
  944. ## `new BasePlugin(uppy, options?)`
  945. The initial building block for a plugin.
  946. `BasePlugin` does not contain DOM rendering so it can be used for plugins
  947. without an user interface.
  948. :::info
  949. See [`UIPlugin`][] for the extended version with Preact rendering for
  950. interfaces.
  951. :::
  952. :::info
  953. Checkout the [building plugins](/docs/guides/building-plugins) guide.
  954. :::
  955. :::note
  956. If you don’t use any UI plugins, any modern bundler should be able to tree-shake
  957. Preact code away. If you are not using a bundler that supports tree-shaking,
  958. it’s also possible to import `BasePlugin` like this:
  959. `import BasePlugin from '@uppy/core/lib/BasePlugin.js`.
  960. :::
  961. ### Options
  962. The options passed to `BasePlugin` are all you options you wish to support in
  963. your plugin.
  964. You should pass the options to `super` in your plugin class:
  965. ```js
  966. class MyPlugin extends BasePlugin {
  967. constructor(uppy, opts) {
  968. super(uppy, opts);
  969. }
  970. }
  971. ```
  972. ### Methods
  973. #### `setOptions(options)`
  974. Options passed during initialization can also be altered dynamically with
  975. `setOptions`.
  976. #### `getPluginState()`
  977. Retrieves the plugin state from the `Uppy` class. Uppy keeps a `plugins` object
  978. in state in which each key is the plugin’s `id`, and the value its state.
  979. #### `setPluginState()`
  980. Set the plugin state in the `Uppy` class. Uppy keeps a `plugins` object in state
  981. in which each key is the plugin’s `id`, and the value its state.
  982. #### `install()`
  983. The `install` method is ran once, when the plugin is added to Uppy with
  984. `.use()`. Use this to initialize the plugin.
  985. For example, if you are creating a pre-processor (such as
  986. [@uppy/compressor](/docs/compressor)) you must add it:
  987. ```js
  988. install () {
  989. this.uppy.addPreProcessor(this.prepareUpload)
  990. }
  991. ```
  992. Another common thing to do when creating a
  993. [UI plugin](#new-uipluginuppy-options) is to [`mount`](#mounttarget) it to the
  994. DOM:
  995. ```js
  996. install () {
  997. const { target } = this.opts
  998. if (target) {
  999. this.mount(target, this)
  1000. }
  1001. }
  1002. ```
  1003. #### `uninstall()`
  1004. The `uninstall` method is ran once, when the plugin is removed from Uppy. This
  1005. happens when `.close()` is called or when the plugin is destroyed in a framework
  1006. integration.
  1007. Use this to clean things up.
  1008. For instance when creating a pre-processor, uploader, or post-processor to
  1009. remove it:
  1010. ```js
  1011. uninstall () {
  1012. this.uppy.removePreProcessor(this.prepareUpload)
  1013. }
  1014. ```
  1015. When creating a [UI plugin](#new-uipluginuppy-options) you should
  1016. [`unmount`](#unmount) it from the DOM:
  1017. ```js
  1018. uninstall () {
  1019. this.unmount()
  1020. }
  1021. ```
  1022. #### `i18nInit`
  1023. Call `this.i18nInit()` once in the constructor of your plugin class to
  1024. initialize [internationalisation](/docs/locales).
  1025. #### `addTarget`
  1026. You can use this method to make your plugin a `target` for other plugins. This
  1027. is what `@uppy/dashboard` uses to add other plugins to its UI.
  1028. #### `update`
  1029. Called on each state update. You will rarely need to use this, unless if you
  1030. want to build a UI plugin using something other than Preact.
  1031. #### `afterUpdate`
  1032. Called after every state update with a debounce, after everything has mounted.
  1033. ## `new UIPlugin(uppy, options?)`
  1034. `UIPlugin` extends [`BasePlugin`][] to add rendering with
  1035. [Preact](https://preactjs.com/). Use this when you want to create an user
  1036. interface or an addition to one, such as [Dashboard][].
  1037. :::info
  1038. See [`BasePlugin`][] for the initial building block for all plugins.
  1039. :::
  1040. :::info
  1041. Checkout the [building plugins](/docs/guides/building-plugins) guide.
  1042. :::
  1043. ### Options
  1044. The options passed to `UIPlugin` are all you options you wish to support in your
  1045. plugin.
  1046. You should pass the options to `super` in your plugin class:
  1047. ```js
  1048. class MyPlugin extends UIPlugin {
  1049. constructor(uppy, opts) {
  1050. super(uppy, opts);
  1051. }
  1052. }
  1053. ```
  1054. In turn these are also passed to the underlying `BasePlugin`.
  1055. ### Methods
  1056. All the methods from [`BasePlugin`][] are also inherited into `UIPlugin`.
  1057. #### `mount(target)`
  1058. Mount this plugin to the `target` element. `target` can be a CSS query selector,
  1059. a DOM element, or another Plugin. If `target` is a Plugin, the source (current)
  1060. plugin will register with the target plugin, and the latter can decide how and
  1061. where to render the source plugin.
  1062. #### `onMount()`
  1063. Called after Preact has rendered the components of the plugin.
  1064. #### `unmount`
  1065. Removing the plugin from the DOM. You generally don’t need to override it but
  1066. you should call it from [`uninstall`](#uninstall).
  1067. The default is:
  1068. ```js
  1069. unmount () {
  1070. if (this.isTargetDOMEl) {
  1071. this.el?.remove()
  1072. }
  1073. this.onUnmount()
  1074. }
  1075. ```
  1076. #### `onUnmount()`
  1077. Called after the elements have been removed from the DOM. Can be used to do some
  1078. clean up or other side-effects.
  1079. #### `render()`
  1080. Render the UI of the plugin. Uppy uses [Preact](https://preactjs.com) as its
  1081. view engine, so `render()` should return a Preact element. `render` is
  1082. automatically called by Uppy on each state change.
  1083. #### `update(state)`
  1084. Called on each state update. You will rarely need to use this, unless if you
  1085. want to build a UI plugin using something other than Preact.
  1086. ## `debugLogger()`
  1087. Logger with extra debug and warning logs for during development.
  1088. ```js
  1089. import { Uppy, debugLogger } from '@uppy/core';
  1090. new Uppy({ logger: debugLogger });
  1091. ```
  1092. :::info
  1093. You can also enable this logger by setting [`debug`](#debug) to `true`.
  1094. :::
  1095. The default value of [`logger`](#logger) is `justErrorsLogger`, which looks like
  1096. this:
  1097. ```js
  1098. // Swallow all logs, except errors.
  1099. // default if logger is not set or debug: false
  1100. const justErrorsLogger = {
  1101. debug: () => {},
  1102. warn: () => {},
  1103. error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
  1104. };
  1105. ```
  1106. `debugLogger` sends extra debugging and warning logs which could be helpful
  1107. during development:
  1108. ```js
  1109. // Print logs to console with namespace + timestamp,
  1110. // set by logger: Uppy.debugLogger or debug: true
  1111. const debugLogger = {
  1112. debug: (...args) => console.debug(`[Uppy] [${getTimeStamp()}]`, ...args),
  1113. warn: (...args) => console.warn(`[Uppy] [${getTimeStamp()}]`, ...args),
  1114. error: (...args) => console.error(`[Uppy] [${getTimeStamp()}]`, ...args),
  1115. };
  1116. ```
  1117. ## Frequently asked questions
  1118. ### How do I allow duplicate files?
  1119. You can allow all files, even duplicate files, with
  1120. [`onBeforeFileAdded`](#onbeforefileadded). This will override the file if it has
  1121. not been uploaded. If you upload a duplicate file again it depends on your
  1122. upload plugin and backend how it is handled.
  1123. ```js
  1124. const uppy = new Uppy({
  1125. // ...
  1126. onBeforeFileAdded: () => true,
  1127. ```
  1128. [dashboard]: /docs/dashboard
  1129. [`baseplugin`]: #new-basepluginuppy-options
  1130. [`uiplugin`]: #new-uipluginuppy-options