-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathuppy-core.mdx
1594 lines (1114 loc) · 42.3 KB
/
uppy-core.mdx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
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 file metadata. Any file metadata should be JSON-serializable.
#### `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.
:::
<a 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');
```
#### `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) => {