Guide
Uploads & Streaming
How files flow into each driver, including streaming, multipart uploads, cancellation, and progress
All drivers accept a WHATWG ReadableStream<Uint8Array>:
const stream = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode("file content"));
controller.close();
},
});
const result = await client.upload(stream, {
filename: "report.pdf",
path: "invoices/2024",
mimeType: "application/pdf",
});Streaming behavior per driver
| Driver | Behavior |
|---|---|
LocalDriver | True streaming. The web stream is piped to disk via Node.js streams with backpressure. Memory usage stays constant regardless of file size. Enforces maxSizeBytes while streaming. |
S3Driver | Streams with bounded memory, always. With options.size (≤ 5 GiB) the payload is sent as a SigV4 aws-chunked body whose chunks are signed lazily as they are read (backpressure preserved, zero buffering). Without a known size, or beyond 5 GiB, the driver falls back to a multipart upload, reading the stream into part-sized buffers (default 8 MiB, minimum 5 MiB), so peak memory stays bounded. |
GCSDriver | Streams with bounded memory. Files up to chunkSize (default 8 MiB) go up in one multipart/related request; larger or unknown sizes use a resumable session, one chunk in memory at a time. |
AzureDriver | Streams with bounded memory. Files up to blockSize (default 8 MiB) are one Put Blob; larger or unknown sizes are staged block by block and committed with Put Block List. |
SupabaseDriver | Streams with bounded memory. Up to 6 MiB is one request; a known larger size uses TUS in 6 MiB chunks; an unknown larger size is streamed as one request body. |
CloudinaryDriver | Streams with bounded memory. Files up to chunkSize (default 20 MiB) go up in one request; larger ones use Cloudinary's chunked upload, holding about one chunk in memory at a time. Enforces maxSizeBytes while streaming. |
When the size is known, pass it to unlock the leanest (single-request) streaming path:
const result = await client.upload(stream, {
filename: "report.pdf",
path: "invoices/2024",
mimeType: "application/pdf",
size: bytes,
});Without size, S3Driver still streams with bounded memory via a multipart upload. If the stream ends before or after the declared size, the upload is aborted and fails with a validation error instead of silently storing a corrupted object.
Multipart uploads
S3Driver splits large objects into parts via the S3 multipart flow (CreateMultipartUpload → UploadPart → CompleteMultipartUpload) in three situations:
- the size is unknown: the stream is read into part-sized buffers instead of being buffered whole;
- the object exceeds 5 GiB, the single-
PUTcap; forceMultipart: trueis set.
Multipart parts are uploaded sequentially as the stream fills each buffer, so peak memory is bounded by partSize (default 8 MiB, minimum 5 MiB) regardless of object size. If the stream mismatches a declared size, the driver aborts the in-flight multipart upload and throws a validation error.
CloudinaryDriver uploads files larger than chunkSize in chunks (X-Unique-Upload-Id + Content-Range), so very large files never sit in memory whole. LocalDriver has no concept of parts because it streams straight to disk.
Cancelling uploads
Pass an AbortSignal in UploadOptions to cancel an in-flight upload. On abort, every driver rejects with a DOMException named AbortError (detectable via err.name === "AbortError" or abortError() from @fileway/core):
const controller = new AbortController();
const upload = client.upload(stream, {
filename: "large.bin",
signal: controller.signal,
});
controller.abort();
try {
await upload;
} catch (err) {
if (err.name === "AbortError") {
// cancelled cleanly
}
}| Driver | Behavior on abort |
|---|---|
LocalDriver | Destroys the source and destination streams and unlinks the partial file, so nothing is left on disk. |
S3Driver | Cancels the request and source stream. For multipart uploads it first sends AbortMultipartUpload so no orphaned parts remain in the bucket. |
GCSDriver | Cancels the request and source stream, then deletes the resumable session. |
AzureDriver | Cancels the request and source stream. Staged blocks are never committed and Azure discards them. |
SupabaseDriver | Cancels the request and source stream, and terminates an unfinished TUS upload. |
CloudinaryDriver | Aborts the upload request. |
Tracking upload progress
Pass onProgress in UploadOptions to receive { bytes, total?, progress? } as chunks flow through the stream. total and progress (0..1) are present only when options.size is known; otherwise only cumulative bytes are reported.
const result = await client.upload(stream, {
filename: "large.bin",
size: totalBytes,
onProgress: ({ bytes, progress }) => {
updateProgressBar(progress ?? bytes / totalBytes);
},
});Event cadence is adaptive: a significant chunk (≥ 256 KiB, or ≥ 5% of a known total) reports immediately, while small chunks on fast streams are coalesced to at most one event per 100 ms. An exact final event always fires (bytes === total, progress === 1), and no event fires on abort. Progress is measured at the client layer as bytes leave the source stream: Local reports as bytes hit disk, S3 as bytes are streamed or buffered into parts, and Cloudinary as bytes are read into each chunk.
Retrying uploads
A ReadableStream is consumed after one read, so to retry an upload Fileway needs a way to re-produce the payload per attempt. Pass streamFactory (a function returning a fresh stream) to enable retry. The source must be re-readable (a file path, in-memory bytes, or a re-fetchable URL); a one-shot feed cannot be retried.
const result = await client.upload(createReadStream(file), {
filename: "photo.jpg",
size: stat.size,
streamFactory: () => createReadStream(file), // fresh stream per retry attempt
});Configure backoff with the client's retry option (e.g. maxRetries, baseDelayMs), and set retry.idleTimeoutMs so an attempt that hangs is cancelled and retried instead of waiting forever (see Timing out stuck attempts). Without streamFactory, a failed upload throws immediately, with no retry. Retried uploads re-transmit the payload, so they cost N+1 egresss on N failures. See Retries for the full configuration and which failures are retried.
Upload links
With app-signed links configured, your server can hand a browser a link to upload one file directly, without sharing any credentials:
// On your server, after checking the user may upload:
const link = await client.getPresignedUploadUrl({
filename: "avatar.png",
path: "avatars",
id: user.id,
mimeType: "image/png",
maxSize: 5 * 1024 * 1024,
expiresIn: 300,
});
// In the browser:
await fetch(link.url, { method: link.method, headers: link.headers, body: file });- The link fixes the filename, folder, id, content type and size limit; changing any of them makes it fail. Reusing the link overwrites the same file.
maxSizedefaults to the driver'smaxSizeBytes. If the driver has no limit,maxSizeis required.- The body is counted as it arrives, so a missing or false
Content-Lengthcannot exceed the limit (413). - The upload runs through
client.upload: your middleware, plugins and events all apply. The response is201with{ id, path, size }. - For browsers on another origin, list it in
links.cors. link.pathis where the file will be stored, so you can save it before the upload happens.
Direct upload links
On S3 (and S3-compatible services such as R2 and MinIO), Google Cloud Storage and Azure, a link can also point straight at the bucket. The file then goes from the browser to the provider without passing through your app, so large uploads cost your server no bandwidth and are not limited by your host's request size (about 4.5 MB on Vercel Functions).
// On your server:
const link = await client.getPresignedUploadUrl({
filename: "demo.mp4",
path: "videos",
mimeType: "video/mp4",
size: file.size, // sent by the browser before uploading
maxSize: 500 * 1024 * 1024,
direct: true,
});
// In the browser: the same call as for app-signed links.
await fetch(link.url, { method: link.method, headers: link.headers, body: file });| Through your app (default) | Direct | |
|---|---|---|
| Where the bytes go | Your app, then the provider | Straight to the provider |
| Needs | links in the client config | A driver that supports it, with signing credentials |
Middleware, plugins, upload event | Run | Skipped (only creating the link is logged, as a getPresignedUrl event) |
| Size limit | Enforced while streaming | Enforced by the provider (S3, Google Cloud); not enforced on Azure |
- Which one you get:
direct: trueasks for a direct link anddirect: falsefor one through your app. Withoutdirect, links go through your app whenlinksis configured, and direct otherwise. Existing apps keep their middleware and events unless they opt in. - S3 needs the exact size. S3 can only enforce an exact length on a signed upload, so pass
size; any other length is rejected. One link uploads up to 5 GiB. - Google Cloud enforces
maxSize(or the exactsize, when given) through thex-goog-content-length-rangeheader inlink.headers. Send every header inlink.headersas is. It needscredentialsorserviceAccount. - Azure cannot limit the size of a direct upload. Links expire within 15 minutes, and if the size matters, check it after the upload with
client.stat(link.path). It needsaccountKey. One link uploads up to 5000 MiB. - After the upload, confirm it with
client.stat(link.path), and record it yourself if you rely on upload events, since your app never sees the request. - CORS: the browser talks to the bucket, so the bucket needs a CORS rule allowing
PUTfrom your site's origin with the headers inlink.headers(content-type, plusx-goog-content-length-rangeon Google Cloud andx-ms-blob-typeon Azure). Set it in the provider's console or CLI. - Checking support in code: a driver that can issue direct links sets
driver.capabilities.directUploadto{ enforcesSize, maxExpiresIn }.
Safe retries and upload status
A network failure is ambiguous: the provider may have stored the file even though its response never reached you (a reset connection, a timeout, a proxy that dropped the reply). Fileway handles this with a stable upload ID:
- Every
upload()call gets oneid(generated, or yours viaoptions.id), and every retry of that call reuses it, so the stored name never changes between attempts. - The client also gives the driver a per-call token (
context.uploadToken, the third argument ofdriver.upload), which the driver stores with the object (S3 object metadata, Cloudinary context, and so on). - When an attempt fails with a retryable error, the client first asks the driver whether that object already landed. If it did, with this call's token and the expected size, the upload succeeds without re-sending anything. This works even without
streamFactory. - Only if the object is not there does the client retry (with
streamFactory) or throw.
Pass your own id to make an upload idempotent across processes, for example a job that may run twice:
const result = await client.upload(stream, {
filename: "invoice.pdf",
path: "invoices",
id: `invoice_${invoice.id}`, // same id on every run: a re-run overwrites, never duplicates
});Reusing an id overwrites that object; that is what makes it safe to repeat. IDs are 1 to 128 characters of A-Z a-z 0-9 _ -.
Checking an upload's status
getUploadStatus(id, { filename, path }) asks the storage provider directly, so it works from any process, even after a crash:
const status = await client.getUploadStatus(`invoice_${invoice.id}`, {
filename: "invoice.pdf",
path: "invoices",
});
switch (status.state) {
case "complete": // status.object has path, url, size and driver metadata
case "pending": // started but not finished (S3 multipart, Local partial file)
case "missing": // never stored
case "unsupported": // the driver cannot report status
}| Driver | complete | pending | Notes |
|---|---|---|---|
S3Driver | HEAD on the object | Open multipart upload for the key | Token stored as x-amz-meta-fileway-upload-token |
GCSDriver | Object metadata GET | Not available | Token stored as custom metadata fileway-upload-token |
AzureDriver | HEAD on the blob | Blocks staged but not committed | Token stored as x-ms-meta-fileway_upload_token |
SupabaseDriver | GET /object/info | Not available | Token stored in user metadata |
LocalDriver | stat on the file | A .partial file is still being written | Writes to a temp file and renames it into place, so a failed retry never damages a finished file. No token; recovery checks size |
CloudinaryDriver | Admin API resource lookup | Not available | Token stored in context. Public IDs are <folder>/<id> (or <id> on dynamic-folder accounts) |
Future: async producers (planned).
streamFactoryis currently sync-only: it must return the stream directly. An async (Promise-returning) variant is a planned enhancement, which would let you pass sources likefetch(url).then((r) => r.body)to re-fetch the payload per attempt without holding it in memory. Until then, on non-Node runtimes use a sync in-memory producer such asnew Blob([bytes]).stream()in browsers/edge/Workers, orDeno.open(path).readablein Deno.
Was this page helpful?