0
# Core Uppy Class
1
2
The Core Uppy class is the central orchestrator for all file upload operations. It manages files, state, plugins, and the upload lifecycle through a comprehensive API that supports both programmatic and event-driven interactions.
3
4
## Capabilities
5
6
### Constructor
7
8
Creates a new Uppy instance with optional configuration.
9
10
```typescript { .api }
11
/**
12
* Create new Uppy instance
13
* @param options - Configuration options for the Uppy instance
14
*/
15
constructor(options?: UppyOptions<M, B>);
16
```
17
18
**Usage Example:**
19
20
```typescript
21
import { Uppy } from "uppy";
22
23
const uppy = new Uppy({
24
debug: true,
25
autoProceed: false,
26
restrictions: {
27
maxFileSize: 10 * 1024 * 1024, // 10MB
28
maxNumberOfFiles: 5,
29
allowedFileTypes: ['image/*', '.pdf']
30
},
31
meta: {
32
username: 'john_doe'
33
}
34
});
35
```
36
37
### File Management
38
39
Comprehensive file management operations including adding, removing, and retrieving files.
40
41
```typescript { .api }
42
/**
43
* Add a single file to Uppy
44
* @param file - File object or file options
45
* @returns File ID of the added file
46
*/
47
addFile(file: UppyFile<M, B> | AddFileOptions<M, B>): string;
48
49
/**
50
* Add multiple files to Uppy
51
* @param files - Array of file objects or file options
52
*/
53
addFiles(files: (UppyFile<M, B> | AddFileOptions<M, B>)[]): void;
54
55
/**
56
* Remove a specific file from Uppy
57
* @param fileId - ID of the file to remove
58
*/
59
removeFile(fileId: string): void;
60
61
/**
62
* Remove multiple files from Uppy
63
* @param fileIds - Array of file IDs to remove (optional, defaults to all files)
64
*/
65
removeFiles(fileIds?: string[]): void;
66
67
/**
68
* Get a specific file by ID
69
* @param fileId - ID of the file to retrieve
70
* @returns File object or undefined if not found
71
*/
72
getFile(fileId: string): UppyFile<M, B> | undefined;
73
74
/**
75
* Get all files currently in Uppy
76
* @returns Array of all file objects
77
*/
78
getFiles(): UppyFile<M, B>[];
79
80
/**
81
* Remove all files from Uppy
82
*/
83
clear(): void;
84
```
85
86
**Usage Examples:**
87
88
```typescript
89
// Add file from File input
90
const fileInput = document.querySelector('#file-input') as HTMLInputElement;
91
if (fileInput.files?.[0]) {
92
const fileId = uppy.addFile({
93
name: fileInput.files[0].name,
94
type: fileInput.files[0].type,
95
data: fileInput.files[0],
96
meta: { source: 'file-input' }
97
});
98
}
99
100
// Add files with restrictions check
101
uppy.addFiles([
102
{
103
name: 'document.pdf',
104
type: 'application/pdf',
105
data: pdfBlob,
106
meta: { category: 'documents' }
107
},
108
{
109
name: 'image.jpg',
110
type: 'image/jpeg',
111
data: imageFile
112
}
113
]);
114
115
// Get and modify file metadata
116
const file = uppy.getFile('file_id');
117
if (file) {
118
uppy.setFileMeta(file.id, {
119
caption: 'Updated caption',
120
tags: ['important', 'work']
121
});
122
}
123
```
124
125
### Upload Control
126
127
Control upload operations including starting, pausing, resuming, retrying, and canceling uploads.
128
129
```typescript { .api }
130
/**
131
* Start upload process for all files
132
* @returns Promise resolving to upload result
133
*/
134
upload(): Promise<UploadResult<M, B>>;
135
136
/**
137
* Pause all ongoing uploads
138
*/
139
pauseAll(): void;
140
141
/**
142
* Resume all paused uploads
143
*/
144
resumeAll(): void;
145
146
/**
147
* Retry all failed uploads
148
* @returns Promise resolving to upload result
149
*/
150
retryAll(): Promise<UploadResult<M, B>>;
151
152
/**
153
* Retry upload for a specific file
154
* @param fileId - ID of the file to retry
155
* @returns Promise resolving to upload result
156
*/
157
retryUpload(fileId: string): Promise<UploadResult<M, B>>;
158
159
/**
160
* Cancel all ongoing uploads
161
*/
162
cancelAll(): void;
163
```
164
165
**Usage Examples:**
166
167
```typescript
168
// Start upload with result handling
169
uppy.upload().then((result) => {
170
console.log('Successful uploads:', result.successful);
171
console.log('Failed uploads:', result.failed);
172
173
if (result.failed.length > 0) {
174
console.log('Some uploads failed, retrying...');
175
return uppy.retryAll();
176
}
177
}).catch((error) => {
178
console.error('Upload failed:', error);
179
});
180
181
// Upload with pause/resume control
182
uppy.upload();
183
setTimeout(() => uppy.pauseAll(), 5000); // Pause after 5 seconds
184
setTimeout(() => uppy.resumeAll(), 10000); // Resume after 10 seconds
185
```
186
187
### Plugin Management
188
189
Manage Uppy plugins including installation, removal, and retrieval.
190
191
```typescript { .api }
192
/**
193
* Install a plugin to the Uppy instance
194
* @param plugin - Plugin constructor/class
195
* @param options - Plugin-specific options
196
* @returns Uppy instance for chaining
197
*/
198
use<T extends BasePlugin<any, any, any>>(
199
plugin: T,
200
options?: T extends BasePlugin<infer Options, any, any> ? Options : never
201
): this;
202
203
/**
204
* Remove a plugin from the Uppy instance
205
* @param instance - Plugin instance to remove
206
*/
207
removePlugin(instance: BasePlugin<any, any, any>): void;
208
209
/**
210
* Get a plugin instance by ID
211
* @param id - Plugin ID
212
* @returns Plugin instance or undefined if not found
213
*/
214
getPlugin<T extends BasePlugin<any, any, any>>(id: string): T | undefined;
215
```
216
217
**Usage Examples:**
218
219
```typescript
220
import { Uppy, Dashboard, Tus, XHRUpload } from "uppy";
221
222
// Chain plugin installations
223
const uppy = new Uppy()
224
.use(Dashboard, {
225
target: '#uppy-dashboard',
226
inline: true
227
})
228
.use(Tus, {
229
endpoint: 'https://tusd.tusdemo.net/files/'
230
});
231
232
// Get plugin instance for configuration
233
const dashboard = uppy.getPlugin('Dashboard');
234
if (dashboard) {
235
dashboard.openModal();
236
}
237
238
// Remove and replace plugin
239
const tusPlugin = uppy.getPlugin('Tus');
240
if (tusPlugin) {
241
uppy.removePlugin(tusPlugin);
242
uppy.use(XHRUpload, {
243
endpoint: '/api/upload'
244
});
245
}
246
```
247
248
### State Management
249
250
Access and modify the internal Uppy state including global and file-specific metadata.
251
252
```typescript { .api }
253
/**
254
* Get current Uppy state
255
* @returns Complete state object
256
*/
257
getState(): State<M, B>;
258
259
/**
260
* Update Uppy state with partial state object
261
* @param patch - Partial state object to merge
262
*/
263
setState(patch: Partial<State<M, B>>): void;
264
265
/**
266
* Set global metadata for all files
267
* @param data - Metadata object to set
268
*/
269
setMeta(data: Partial<M>): void;
270
271
/**
272
* Set metadata for a specific file
273
* @param fileId - ID of the file to update
274
* @param data - Metadata object to set
275
*/
276
setFileMeta(fileId: string, data: Partial<M>): void;
277
```
278
279
**Usage Examples:**
280
281
```typescript
282
// Get current state
283
const state = uppy.getState();
284
console.log('Current files:', Object.keys(state.files).length);
285
console.log('Total progress:', state.totalProgress);
286
287
// Set global metadata
288
uppy.setMeta({
289
projectId: 'abc123',
290
uploadedBy: 'user@example.com'
291
});
292
293
// Set file-specific metadata
294
uppy.setFileMeta('file_id', {
295
caption: 'Profile picture',
296
altText: 'User avatar image'
297
});
298
299
// Listen for state changes
300
uppy.on('state-update', (prev, next, patch) => {
301
console.log('State updated:', patch);
302
});
303
```
304
305
### Event System
306
307
Comprehensive event system for listening to upload lifecycle, file management, and plugin interactions.
308
309
```typescript { .api }
310
/**
311
* Add event listener
312
* @param event - Event name
313
* @param callback - Event handler function
314
* @returns Uppy instance for chaining
315
*/
316
on<K extends keyof UppyEventMap<M, B>>(
317
event: K,
318
callback: UppyEventMap<M, B>[K]
319
): this;
320
321
/**
322
* Remove event listener
323
* @param event - Event name
324
* @param callback - Event handler function to remove
325
* @returns Uppy instance for chaining
326
*/
327
off<K extends keyof UppyEventMap<M, B>>(
328
event: K,
329
callback: UppyEventMap<M, B>[K]
330
): this;
331
332
/**
333
* Emit an event
334
* @param event - Event name
335
* @param args - Event arguments
336
*/
337
emit<K extends keyof UppyEventMap<M, B>>(
338
event: K,
339
...args: Parameters<UppyEventMap<M, B>[K]>
340
): void;
341
```
342
343
**Usage Examples:**
344
345
```typescript
346
// File management events
347
uppy.on('file-added', (file) => {
348
console.log('File added:', file.name);
349
});
350
351
uppy.on('file-removed', (file, reason) => {
352
console.log('File removed:', file.name, 'Reason:', reason);
353
});
354
355
// Upload lifecycle events
356
uppy.on('upload-start', (data) => {
357
console.log('Upload started for files:', data.fileIDs);
358
});
359
360
uppy.on('upload-progress', (file, progress) => {
361
console.log(`${file.name}: ${progress.percentage}%`);
362
});
363
364
uppy.on('upload-success', (file, response) => {
365
console.log('Upload successful:', file.name, response);
366
});
367
368
uppy.on('upload-error', (file, error, response) => {
369
console.error('Upload failed:', file.name, error);
370
});
371
372
uppy.on('complete', (result) => {
373
console.log('All uploads complete');
374
console.log('Successful:', result.successful.length);
375
console.log('Failed:', result.failed.length);
376
});
377
378
// Remove event listener
379
const progressHandler = (file, progress) => {
380
console.log(`Progress: ${progress.percentage}%`);
381
};
382
383
uppy.on('upload-progress', progressHandler);
384
// Later...
385
uppy.off('upload-progress', progressHandler);
386
```
387
388
## Core Configuration Types
389
390
```typescript { .api }
391
interface UppyOptions<M extends Meta = {}, B extends Body = {}> {
392
id?: string;
393
autoProceed?: boolean;
394
allowMultipleUploads?: boolean;
395
debug?: boolean;
396
restrictions?: Restrictions;
397
meta?: M;
398
onBeforeFileAdded?: (
399
currentFile: UppyFile<M, B>,
400
files: { [fileId: string]: UppyFile<M, B> }
401
) => UppyFile<M, B> | boolean | undefined;
402
onBeforeUpload?: (
403
files: { [fileId: string]: UppyFile<M, B> }
404
) => { [fileId: string]: UppyFile<M, B> } | boolean | undefined;
405
locale?: Locale;
406
store?: Store;
407
logger?: Logger;
408
infoTimeout?: number;
409
}
410
411
interface AddFileOptions<M extends Meta = {}, B extends Body = {}> {
412
name: string;
413
type?: string;
414
data: Blob | File;
415
meta?: M;
416
source?: string;
417
isRemote?: boolean;
418
}
419
420
interface Restrictions {
421
maxFileSize?: number | null;
422
minFileSize?: number | null;
423
maxTotalFileSize?: number | null;
424
maxNumberOfFiles?: number | null;
425
minNumberOfFiles?: number | null;
426
allowedFileTypes?: string[] | null;
427
requiredMetaFields?: string[];
428
}
429
```
430
431
## Key Events
432
433
```typescript { .api }
434
interface UppyEventMap<M extends Meta = {}, B extends Body = {}> {
435
// File events
436
'file-added': (file: UppyFile<M, B>) => void;
437
'file-removed': (file: UppyFile<M, B>, reason?: string) => void;
438
'files-added': (files: UppyFile<M, B>[]) => void;
439
440
// Upload events
441
'upload': (data: { id: string; fileIDs: string[] }) => void;
442
'upload-start': (data: { id: string; fileIDs: string[] }) => void;
443
'upload-progress': (file: UppyFile<M, B>, progress: FileProgress) => void;
444
'upload-success': (file: UppyFile<M, B>, response: UploadSuccessResponse<B>) => void;
445
'upload-error': (file: UppyFile<M, B>, error: Error, response?: UploadErrorResponse<M, B>) => void;
446
'upload-retry': (fileId: string) => void;
447
'complete': (result: UploadResult<M, B>) => void;
448
449
// State events
450
'state-update': (prev: State<M, B>, next: State<M, B>, patch: Partial<State<M, B>>) => void;
451
'info-visible': () => void;
452
'info-hidden': () => void;
453
454
// Restriction events
455
'restriction-failed': (file: UppyFile<M, B>, error: Error) => void;
456
457
// Cancel events
458
'cancel-all': () => void;
459
'file-editor:cancel': (file?: UppyFile<M, B>) => void;
460
'file-editor:complete': (file?: UppyFile<M, B>) => void;
461
}
462
```