The Uploader class let you define your own file upload strategy.

There are two types of uploaders you can define:

  • Stateless uploader: This uploader handles each file individually. It's useful when you're uploading files through an API in your backend.
  • Stateful uploader: This uploader handles multiple files at once. It's useful when you need to orchestrate the upload of several files simultaneously.

Stateless Uploader

In case you don't need to tie the upload of one file to the upload of another, you can use a stateless uploader.

Define an UploadHandler function that takes a File and returns a Promise<string>.

const uploader = new Uploader(async (file: File) => {
const response = await fetch('https://example.com/upload', {
method: 'POST',
body: file,
});

if (!response.ok) {
throw new Error('Failed to upload');
}

return response.headers.get('Location')!;
});

Stateful Uploader

In case you need to create more complex upload strategies, you can extend the Uploader class.

This is useful when you need to upload multiple files at once.

class MyUploader extends Uploader {
private files: File[] = [];

async initialize() {
this.files = [];
}

async addFile(file: File) {
this.files.push(file);

return computeFinalURI(file);
}

async finalize() {
// Upload all files according to your strategy
}
}

const uploader = new MyUploader();

You must override the addFile method with the logic to upload the file.

You can also override the initialize and finalize methods to handle the upload session lifecycle. Use the initialize method to prepare your uploader internal state (e.g. reset from a previous upload), and the finalize method to, for example, perform a bulk upload of all files.

Hierarchy (view full)

Implements

Constructors

Constructors