Generated from
upload'ssrc/manifest.ts— the same source that powersllms.txtand MCPget_api. Do not edit this page by hand; edit the manifest. For the conceptual guide, see upload.
A reactive upload queue. createUploader({ transport }) validates files (size, type, image dimensions, magic-number sniffing, your own rule), uploads them with a concurrency limit, retries only failures a retry can fix (network, 408, 429 with Retry-After honoured, 5xx; never a 4xx), pauses, resumes, cancels and reports progress, speed and time left as signals that never go backwards and are written once per animation frame. xhrTransport sends with XMLHttpRequest because fetch has no upload progress; pass an @pyreon/http client and its base URL, headers and middleware apply. Headless <FileDrop> and <FilePicker> (keyboard operable, labelled, with a live region for refusals; SSR-safe), a form adapter and a query mutation adapter are separate entries. chunkedTransport, s3Transport (presigned single and multipart, no SDK) and tusTransport (tus 1.0) resume after a failure, a pause or a page reload (createResumeStore persists the state). useFilePicker and useFileDrop are the state of a picker and a drop zone: enter and leave are counted across children, files are judged while dragging, folders are read, paste is an option, and picking the same file twice works. @pyreon/upload/core has the pure parts (validation, sniffType, chunk planning, progress math, the error taxonomy) with no dependencies. Dispose aborts in-flight requests and removes timers, listeners and object URLs; creating anything on the server is inert. Client validation is UX: the server must check type, size and content.
Multiplatform
Tier: Web-only — the browser package; the native story is stated below
not lowered by PMTC: it is built on the browser File, Blob, XMLHttpRequest, DataTransfer and object URL APIs, which have no Swift or Kotlin counterpart in the compiler yet; native apps pick files with the platform pickers and upload with their own networking
See Multiplatform for the capability matrix and Multiplatform libraries for every package's tier.
Features
A reactive queue: concurrency limit, fair order, pause, resume, cancel, retry, aggregate progress, status and speed as signals
Progress that never goes backwards (also across retries) and is written to signals once per animation frame, however often a transport reports
Retry only what a retry can fix: network errors, timeouts, 408, 425, 429 (Retry-After in seconds or as a date) and 5xx; backoff with jitter; never a 4xx
Validation: size ("10 MB"), accept (MIME, wildcards, extensions), image dimensions, magic-number sniffing, custom; plain-English messages with params for i18n
XHR transport with real upload progress and an optional @pyreon/http client (base URL, auth headers, middleware)
useFilePicker (same file twice works, cancel detected) and useFileDrop (counted enter/leave, folders, paste, judged while dragging)
Dispose leaves nothing: aborts requests, clears timers and listeners, revokes object URLs; inert on the server
Complete example
A full, end-to-end usage of the package:
import { createUploader } from '@pyreon/upload'
import { xhrTransport } from '@pyreon/upload/transport-xhr'
const uploader = createUploader({ transport: xhrTransport({ url: '/api/upload' }), rules: { maxSize: '10 MB', accept: ['image/*'], maxFiles: 5 } })
typeof uploader.add // => 'function'
uploader.status() // => 'idle'Exports
| Symbol | Kind | Summary |
|---|---|---|
createUploader | function | A reactive upload queue. |
useUploader | function | The same queue, for a component: disposed when the component unmounts. |
xhrTransport | function | Upload each file as one request with XMLHttpRequest and report real upload progress. |
xhrHttpTransport | function | The XHR transport as an @pyreon/http transport: it reports upload progress through request.meta.onUploadProgress. |
useFilePicker | function | State for a file picker: open(), the picked files() and inputProps for a hidden input. |
useFileDrop | function | State and handlers for a drop zone: isOver() (enter and leave are counted, so children do not make it flicker),… |
validateFile | function | Check one file against maxSize, minSize, accept, and (asynchronously) image dimensions, sniff and custom. |
validateFileAsync | function | validateFile as a Promise, whichever way it answers. |
validateFiles | function | Check a batch, one array of rejections per file, with maxFiles counted across the batch (and the existing files… |
sniffType | function | The real type of a file by its first bytes, so accept: image/* is not fooled by a renamed .exe. |
sniffBytes | function | sniffType on bytes you already have. |
matchesAccept | function | Does a file match one of the accept patterns: MIME types, wildcards and extensions, ignoring case, as the accept… |
parseSize | function | A size in bytes from a number or text: "10 MB" is 10,000,000 (KB, MB, GB, TB are decimal), "10 MiB" is 10,485,760… |
formatSize | function | A size for a message, in decimal units: 1.5 MB. |
chunkCount | function | How many parts a file has (an empty file has one empty part). |
chunkRange | function | The byte range of one part; slice the file with Blob.slice(start, end). |
planChunks | function | The parts of a file, lazily: a 1 TB file in 5 MB parts is 200,000 parts and is never held as an array. |
suggestChunkSize | function | A part size that keeps a file within maxParts parts (default 10,000, S3's limit) and not below minSize (default 5… |
progressOf | function | Bytes as a Progress, clamped; the ratio of an empty file is 0 until complete. |
sumProgress | function | The progress of several files, by bytes: a big file weighs more. |
monotonic | function | The larger of what was shown and what is reported: progress never goes back. |
remainingMs | function | Time left in ms from a speed in bytes per second; null while the speed is unknown. |
createSpeedMeter | function | A smoothed speed (exponential moving average): record(loaded, now), speed() (null until two samples 250 ms apart),… |
uploadError | function | Build an UploadError. |
isUploadError | function | Whether a value has the shape of an UploadError. |
isRetryableStatus | function | Is this HTTP status worth another attempt? 408, 425, 429 and 5xx are; other 4xx (validation, auth, size) never are. |
parseRetryAfter | function | Retry-After as milliseconds: whole seconds or an HTTP date; a date in the past is 0; anything else is undefined. |
errorFromStatus | function | The error for a failed HTTP response: retryable by isRetryableStatus, with retryAfter and the parsed body. |
toUploadError | function | Any thrown value as an UploadError: an AbortError is aborted; an object with an HTTP status is a server error;… |
defaultBackoff | function | The delay before the next try: 500 ms doubling to a minute, with jitter between half and all of it. |
collectDropped | function | The files of a drop, with folders read and flattened when the browser supports webkitGetAsEntry. |
collectPasted | function | The files on the clipboard (a pasted image); text is not touched. |
chunkedTransport | function | A generic resumable upload in parts with a small server contract: POST BASE (JSON… |
s3Transport | function | Upload straight to S3 (or R2, MinIO, anything with presigned URLs) with no SDK. |
tusTransport | function | The tus 1.0 resumable upload protocol with the creation and termination extensions: POST to create (with… |
createResumeStore | function | Persist resume state in localStorage (or an @pyreon/storage adapter) so an upload continues after a page reload:… |
fingerprint | function | What identifies a file across page loads: name, size, type and last-modified time. |
FileDrop | function | A headless drop zone: a role="button" element (focusable, aria-label, aria-busy, aria-disabled, out of the tab… |
FilePicker | function | A headless picker button: a native <button type="button"> (so Enter and Space work as on any button) that opens the… |
bindFileField | function | Make an uploader's files the value of an @pyreon/form field (form.fields.avatar): the value is the list of accepted… |
fileValidator | function | A validator for useForm({ validators: { avatar: fileValidator({ required: "Choose a photo", rules }) } }): the… |
uploadMutation | function | An upload as an @pyreon/query mutation: useMutation(uploadMutation(uploader)). |
UploadFile | type | One item of a queue: plain data and functions that read signals. |
Uploader | type | The queue returned by createUploader. |
Transport | type | Sends one file. |
FileRule | type | What a file is checked against. |
UploadError | type | Why an upload did not work, and whether a retry can help. |
API
createUploader function — experimental
(options: UploaderOptions) => UploaderA reactive upload queue. Files are validated, then sent by the transport with concurrency at a time (default 3, a whole number from 1). Failures that a retry can fix are retried up to retry.attempts tries in total (default 3) after a delay with jitter (a Retry-After is honoured); 4xx answers and unknown errors are never retried. Progress is written to signals once per animation frame and never decreases. Rejected files stay in the list with their reasons unless keepRejected: false. Created in a component or effect scope it is disposed with it; otherwise call dispose(). Creating one touches no browser API.
Example
typeof createUploader({ transport: { upload: async () => 'ok' } }).add // => 'function'
createUploader({ transport: { upload: async () => 'ok' } }).status() // => 'idle'Common mistakes
Reading a whole file with
FileReaderto upload it: it holds the file in memory and has no upload progress. Pass theFileto a transport, which slices itNever revoking preview object URLs:
preview: truerevokes them on remove, clear and disposeTrusting
file.typeor the extension: it is what the user's machine said. Userules.snifffor the UI and check the content on the serverUsing
fetchfor a large upload and wishing for a progress bar:fetchhas no upload progress. UsexhrTransport
See also: xhrTransport · validateFile · useFileDrop
useUploader function — experimental
(options: UploaderOptions) => UploaderThe same queue, for a component: disposed when the component unmounts.
Example
typeof useUploader({ transport: { upload: async () => 'ok' } }).files // => 'function'xhrTransport function — experimental
(options: { url, method?, field?, headers?, withCredentials?, body?, timeout?, sendMeta?, client? }) => TransportUpload each file as one request with XMLHttpRequest and report real upload progress. The file goes in a multipart field (default file) with the file meta as text fields, unless you build the body. A 2xx answer resolves with the parsed body (JSON when the server says so); 408, 425, 429 and 5xx are retryable (Retry-After honoured), other statuses are not; network failures and timeouts are retryable. With client, the request goes through an @pyreon/http client so its base URL, headers and middleware apply.
Example
typeof xhrTransport({ url: '/upload' }).upload // => 'function'xhrHttpTransport function — experimental
() => (request) => Promise<response>The XHR transport as an @pyreon/http transport: it reports upload progress through request.meta.onUploadProgress. xhrTransport({ client }) uses it; use it directly to send your own requests with progress.
Example
typeof xhrHttpTransport() // => 'function'useFilePicker function — experimental
(options?: { multiple?, accept?, directory?, capture?, onPick?, onCancel? }) => FilePickerState for a file picker: open(), the picked files() and inputProps for a hidden input. The input is emptied after each pick (after the files are copied out), so choosing the same file twice works; a cancelled dialog is reported. With no input rendered, open() makes a detached one. Nothing touches the DOM until open().
Example
typeof useFilePicker({ accept: ['image/*'] }).open // => 'function'
useFilePicker({ multiple: true }).inputProps.multiple // => trueuseFileDrop function — experimental
(options?: { accept?, multiple?, disabled?, directories?, paste?, onDrop?, onReject? }) => FileDropState and handlers for a drop zone: isOver() (enter and leave are counted, so children do not make it flicker), isValid() (the dragged types judged against accept while dragging) and dropProps to spread. Folders are read and flattened when the browser can; paste: true also takes pasted files. Accepted files go to onDrop, the others to onReject.
Example
useFileDrop().isOver() // => false
useFileDrop().isValid() // => nullvalidateFile function — experimental
(file: File | Blob, rules: FileRule) => FileRejection[] | Promise<FileRejection[]>Check one file against maxSize, minSize, accept, and (asynchronously) image dimensions, sniff and custom. An empty array means accepted. Each rejection has a code (too-large, too-small, type, dimensions, custom), a plain English message and params for translation. The answer is synchronous unless a rule has to look inside the file.
Example
validateFile(new File(['x'], 'a.png', { type: 'image/png' }), { maxSize: 10 }) // => []
validateFile(new File(['x'], 'a.png', { type: 'image/png' }), { accept: ['.pdf'] })[0].code // => 'type'validateFileAsync function — experimental
(file, rules) => Promise<FileRejection[]>validateFile as a Promise, whichever way it answers.
Example
typeof validateFileAsync // => 'function'validateFiles function — experimental
(files, rules, existing?) => Promise<FileRejection[][]>Check a batch, one array of rejections per file, with maxFiles counted across the batch (and the existing files already accepted): files past the limit are too-many.
Example
typeof validateFiles // => 'function'sniffType function — experimental
(file: Blob) => Promise<string | null>The real type of a file by its first bytes, so accept: image/* is not fooled by a renamed .exe. Reads 264 bytes with Blob.slice. Known: PNG, JPEG, GIF, WebP, BMP, ICO, TIFF, AVIF, HEIC, PDF, ZIP (also DOCX, XLSX), GZIP, 7z, RAR, MP4, WebM, MP3, OGG, WAV, FLAC, Windows executables, ELF and SVG. null means "cannot tell", not "safe". Never the only check: the server must check the content.
Example
sniffBytes(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) // => 'image/png'
sniffBytes(new Uint8Array([0x4d, 0x5a, 0, 0])) // => 'application/x-msdownload'
sniffBytes(new TextEncoder().encode('hello')) // => nullCommon mistakes
Treating a sniffed type as proof of safety: a polyglot file can start with a PNG header and be something else
sniffBytes function — experimental
(head: Uint8Array) => string | nullsniffType on bytes you already have.
Example
sniffBytes(new Uint8Array([0xff, 0xd8, 0xff, 0xe0])) // => 'image/jpeg'matchesAccept function — experimental
(file: { name?, type }, accept: readonly string[]) => booleanDoes a file match one of the accept patterns: MIME types, wildcards and extensions, ignoring case, as the accept attribute does. An empty list accepts everything.
Example
matchesAccept({ name: 'a.PNG', type: 'image/png' }, ['image/*']) // => true
matchesAccept({ name: 'a.exe', type: '' }, ['.png', 'image/*']) // => falseparseSize function — experimental
(value: number | string) => numberA size in bytes from a number or text: "10 MB" is 10,000,000 (KB, MB, GB, TB are decimal), "10 MiB" is 10,485,760 (KiB, MiB, GiB, TiB are binary). Anything else throws.
Example
parseSize('10 MB') // => 10000000
parseSize('1.5 MiB') // => 1572864
parseSize(512) // => 512formatSize function — experimental
(bytes: number) => stringA size for a message, in decimal units: 1.5 MB.
Example
formatSize(1500) // => '1.5 KB'
formatSize(10000000) // => '10 MB'chunkCount function — experimental
(size: number, chunkSize: number) => numberHow many parts a file has (an empty file has one empty part).
Example
chunkCount(10, 4) // => 3
chunkCount(0, 4) // => 1chunkRange function — experimental
(size, chunkSize, index) => { index, start, end }The byte range of one part; slice the file with Blob.slice(start, end).
Example
chunkRange(10, 4, 2) // => { index: 2, start: 8, end: 10 }planChunks function — experimental
(size, chunkSize) => Generator<Chunk>The parts of a file, lazily: a 1 TB file in 5 MB parts is 200,000 parts and is never held as an array. The file is never read.
Example
[...planChunks(10, 4)].map((c) => [c.start, c.end]) // => [[0, 4], [4, 8], [8, 10]]suggestChunkSize function — experimental
(size, options?: { minSize?, maxParts? }) => numberA part size that keeps a file within maxParts parts (default 10,000, S3's limit) and not below minSize (default 5 MiB).
Example
suggestChunkSize(10) // => 5242880progressOf function — experimental
(loaded, total, complete?) => ProgressBytes as a Progress, clamped; the ratio of an empty file is 0 until complete.
Example
progressOf(50, 200) // => { loaded: 50, total: 200, ratio: 0.25 }sumProgress function — experimental
(list: Progress[]) => ProgressThe progress of several files, by bytes: a big file weighs more.
Example
sumProgress([progressOf(50, 100), progressOf(0, 100)]).ratio // => 0.25monotonic function — experimental
(shown, reported) => numberThe larger of what was shown and what is reported: progress never goes back.
Example
monotonic(70, 30) // => 70remainingMs function — experimental
(loaded, total, speed) => number | nullTime left in ms from a speed in bytes per second; null while the speed is unknown.
Example
remainingMs(1500, 3000, 750) // => 2000
remainingMs(0, 10, null) // => nullcreateSpeedMeter function — experimental
(alpha?) => SpeedMeterA smoothed speed (exponential moving average): record(loaded, now), speed() (null until two samples 250 ms apart), reset().
Example
createSpeedMeter().speed() // => nulluploadError function — experimental
(kind, message, extra?) => UploadErrorBuild an UploadError. A transport rejects with these so the queue knows whether to retry: network and timeout default to retryable, the others not.
Example
uploadError('network', 'down').retryable // => true
uploadError('server', 'bad', { status: 422 }).retryable // => falseisUploadError function — experimental
(x: unknown) => x is UploadErrorWhether a value has the shape of an UploadError.
Example
isUploadError(uploadError('aborted', 'x')) // => true
isUploadError(new Error('x')) // => falseisRetryableStatus function — experimental
(status: number) => booleanIs this HTTP status worth another attempt? 408, 425, 429 and 5xx are; other 4xx (validation, auth, size) never are.
Example
isRetryableStatus(503) // => true
isRetryableStatus(422) // => falseparseRetryAfter function — experimental
(value, now?) => number | undefinedRetry-After as milliseconds: whole seconds or an HTTP date; a date in the past is 0; anything else is undefined.
Example
parseRetryAfter('120') // => 120000
parseRetryAfter('soon') // => undefinederrorFromStatus function — experimental
(status, options?: { retryAfter?, body? }) => UploadErrorThe error for a failed HTTP response: retryable by isRetryableStatus, with retryAfter and the parsed body.
Example
errorFromStatus(429, { retryAfter: '3' }).retryAfter // => 3000
errorFromStatus(422).retryable // => falsetoUploadError function — experimental
(error: unknown) => UploadErrorAny thrown value as an UploadError: an AbortError is aborted; an object with an HTTP status is a server error; an unknown error is not retried (a bug is not weather).
Example
toUploadError(new Error('bug')).retryable // => falsedefaultBackoff function — experimental
(attempt, random?) => numberThe delay before the next try: 500 ms doubling to a minute, with jitter between half and all of it.
Example
defaultBackoff(1, () => 1) // => 500collectDropped function — experimental
(data: DataTransfer, options?) => Promise<File[]>The files of a drop, with folders read and flattened when the browser supports webkitGetAsEntry. Call it from the drop handler: the items are only valid during the event.
Example
typeof collectDropped // => 'function'collectPasted function — experimental
(data: DataTransfer) => File[]The files on the clipboard (a pasted image); text is not touched.
Example
collectPasted(null) // => []chunkedTransport function — experimental
(options: { url, chunkSize?, parallel?, checksum?, headers?, withCredentials?, timeout? }) => TransportA generic resumable upload in parts with a small server contract: POST BASE (JSON { name, size, type, chunkSize, meta }, answers { uploadId }), GET BASE/:id ({ received: number[] }), PUT BASE/:id/parts/:n (raw bytes, optional x-part-sha256), POST BASE/:id/complete (answers the result), DELETE BASE/:id. The file is sliced with Blob.slice, parallel parts at a time (default 3), each with real progress; after every part the state is saved so a retry, a pause or a reload continues from the parts the server has (its list of parts wins over the saved state). A reference handler for the contract is on the docs page.
Example
typeof chunkedTransport({ url: '/api/uploads' }).upload // => 'function'See also: createResumeStore · s3Transport · tusTransport
s3Transport function — experimental
(options: { presign, multipart?, partSize?, parallel?, withCredentials? }) => TransportUpload straight to S3 (or R2, MinIO, anything with presigned URLs) with no SDK. A file up to partSize is one presigned PUT; a bigger one is multipart if you give multipart: { create, signPart, complete, abort?, list? }: your server creates the upload and signs each part, the browser sends the parts with progress and collects the ETags, your server completes it. The part size is at least 5 MiB and never needs more than 10,000 parts. Resumable: the upload id and the parts with their ETags are saved after each part, and list (your ListParts) confirms which exist. Cancelling calls abort. The bucket CORS rule must expose the ETag header.
Example
typeof s3Transport({ presign: async () => ({ url: 'https://bucket.invalid/key' }) }).upload // => 'function'Common mistakes
Presigned URLs that are not scoped: one key, one method, a short expiry, a content-length range for single uploads
tusTransport function — experimental
(options: { endpoint, chunkSize?, metadata?, headers?, withCredentials?, timeout? }) => TransportThe tus 1.0 resumable upload protocol with the creation and termination extensions: POST to create (with Upload-Length and Upload-Metadata), PATCH at the right Upload-Offset, HEAD to ask the offset on a resume, DELETE when the file is cancelled or removed. The upload URL is saved after creation, so a retry, a pause or a reload continues where the server is; a 404 or 410 for a saved URL, or a different length, starts a new upload. Retries are the queue's, not the transport's.
Example
typeof tusTransport({ endpoint: '/files' }).upload // => 'function'createResumeStore function — experimental
(storage: { getItem, setItem, removeItem }, options?: { prefix?, maxAge?, now? }) => ResumeStorePersist resume state in localStorage (or an @pyreon/storage adapter) so an upload continues after a page reload: pass the store as createUploader({ resume }). The state is saved by file fingerprint, loaded when a file is added, and cleared when the upload finishes, fails for good, or is cancelled or removed. Entries expire after maxAge (default 7 days); a corrupt entry is removed; a storage that throws makes saving a no-op.
Example
createResumeStore({ getItem: () => null, setItem: () => {}, removeItem: () => {} }).load({ name: 'a', size: 1, type: '', file: new Blob(['a']) }) // => undefinedfingerprint function — experimental
(file) => stringWhat identifies a file across page loads: name, size, type and last-modified time.
Example
fingerprint({ name: 'a.mp4', size: 10, type: 'video/mp4', file: new File([], 'a.mp4', { lastModified: 5 }) }) // => 'a.mp4|10|video/mp4|5'FileDrop function — experimental
(props: FileIntakeProps) => VNodeA headless drop zone: a role="button" element (focusable, aria-label, aria-busy, aria-disabled, out of the tab order when disabled) that opens the file dialog on click, Enter and Space, takes dropped files (and pasted ones with paste), judges the drag (data-drag-over, data-drop-valid), and applies the rules and accept (case-insensitive) with reasons: accepted files go to onFiles, refused ones to onReject and to the rejected slot, and a visually hidden <output> live region announces what happened. Focus returns to the zone after every drop, pick or refusal. The children can be a function of the state (isOver, isValid, rejections, open, liveRegionProps). Unstyled: style it with class and the data- attributes. The server renders the static markup; hydration adds the behaviour. From @pyreon/upload/components (needs @pyreon/core).
Example
typeof FileDrop // => 'function'Common mistakes
A label that differs from the visible text (WCAG 2.5.3, flagged by axe): make
labelcontain the visible words, or name the zone withlabelledbyPlacing the live region where it is removed and re-added: it must stay in the page for announcements to be read; use
live={false}andstate.liveRegionPropsto place it yourself
See also: FilePicker · useFileDrop
FilePicker function — experimental
(props: FileIntakeProps) => VNodeA headless picker button: a native <button type="button"> (so Enter and Space work as on any button) that opens the file dialog, with the same rules, refusal reasons, live region and focus handling as FileDrop. The same file can be picked twice. children is the label, or a function of the state. From @pyreon/upload/components.
Example
typeof FilePicker // => 'function'bindFileField function — experimental
(uploader, field, options?) => () => voidMake an uploader's files the value of an @pyreon/form field (form.fields.avatar): the value is the list of accepted Files; adding touches the field; the reason a file was rejected is the field's error; and resetting the form (the value goes back to empty) clears the queue. Structural: neither package imports the other. From @pyreon/upload/form.
Example
typeof bindFileField // => 'function'See also: fileValidator
fileValidator function — experimental
(options?: { required?: boolean | string, rules?: FileRule }) => ValidateFnA validator for useForm({ validators: { avatar: fileValidator({ required: "Choose a photo", rules }) } }): the required-file rule, maxFiles, then each file against the rules; the first reason is the error. It answers a Promise only when a rule has to look inside the file. From @pyreon/upload/form.
Example
fileValidator({ required: 'Choose a file' })([]) // => 'Choose a file'
fileValidator({ rules: { maxFiles: 1 } })([new File([], 'a'), new File([], 'b')]) // => 'At most 1 file is allowed.'uploadMutation function — experimental
(uploader) => { mutationFn }An upload as an @pyreon/query mutation: useMutation(uploadMutation(uploader)). mutationFn(files) adds the files and resolves with their UploadFiles when all are done, or rejects with an error that carries the typed uploadError and the file of the first that failed or was rejected. Progress is not mutation state: read uploader.progress(). From @pyreon/upload/query.
Example
typeof uploadMutation({ add: () => [] } as never).mutationFn // => 'function'UploadFile type — experimental
interface UploadFile { id; file; name; size; type; meta; status(); progress(); speed(); remaining(); error(); result(); preview(); attempt(); rejections() }One item of a queue: plain data and functions that read signals.
Example
const f = null as unknown as UploadFileUploader type — experimental
interface Uploader { files(); add(); remove(); clear(); start(); pause(); resume(); cancel(); retry(); progress(); status(); isUploading(); dispose() }The queue returned by createUploader.
Example
const u = null as unknown as UploaderTransport type — experimental
interface Transport { upload(file, ctx: { signal, onProgress, resumeState?, saveResumeState }): Promise<unknown> }Sends one file. Resolve with what the server returned; reject with an UploadError.
Example
const t: Transport = { upload: async () => 'ok' }FileRule type — experimental
interface FileRule { maxSize?; minSize?; accept?; maxFiles?; image?; sniff?; custom? }What a file is checked against.
Example
const rule: FileRule = { maxSize: '10 MB', accept: ['image/*'] }UploadError type — experimental
interface UploadError { kind: "rejected" | "network" | "server" | "aborted" | "timeout"; message; status?; retryable; retryAfter?; body?; cause? }Why an upload did not work, and whether a retry can help.
Example
const e: UploadError = { kind: 'network', message: 'down', retryable: true }Package-level notes
Client validation is UX: Size, type and sniffing checks make the interface friendly; they do not protect the server, because a client can send anything. The server must check type, size and content itself, and must never trust the file name or the declared type.
Progress is monotonic: Progress never decreases. After a retry the transport restarts from zero on the wire, but the number you see holds at its high-water mark until the new attempt passes it. A
cancelfollowed byretryis a new upload and starts at zero.
Why XHR: XMLHttpRequest reports upload progress in every browser.
fetchhas no upload progress event, and streaming request bodies need HTTP/2 and are not available everywhere, soxhrTransportis the reliable baseline.
Retry rules: Retried: network errors, timeouts, 408, 425, 429 and 5xx, after a backoff with jitter (a
Retry-Afterheader, in seconds or as a date, is honoured when longer). Never retried: other 4xx, errors a transport marks non-retryable, unknown thrown errors and aborts.attemptscounts tries in total, the first included.
Previews and object URLs:
preview: truecreates an object URL for images and videos; it is revoked when the file is removed, onclear()and ondispose(). Creating your own withURL.createObjectURLis yours to revoke.
Offline: While
navigator.onLineis false the queue pauses uploads and resumes them when it is back (pauseWhenOffline: falseturns this off). It listens toonlineandofflineonwindowfrom the firstadd()and removes the listeners ondispose().
Server and SSR: Creating an uploader, a picker or a drop zone on the server touches no browser API and starts no timer. Files only exist in the browser;
xhrTransportfails with a clear error if it is ever called where there is no XMLHttpRequest.
Folders and DataTransfer:
uploader.add(dataTransfer)takes the top-level files. To read dropped folders usecollectDropped(whatuseFileDropdoes) from the drop handler: the items are only valid while the event runs.