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

DriverBehavior
LocalDriverTrue 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.
S3DriverStreams 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.
GCSDriverStreams 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.
AzureDriverStreams 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.
SupabaseDriverStreams 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.
CloudinaryDriverStreams 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-PUT cap;
  • forceMultipart: true is 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
  }
}
DriverBehavior on abort
LocalDriverDestroys the source and destination streams and unlinks the partial file, so nothing is left on disk.
S3DriverCancels the request and source stream. For multipart uploads it first sends AbortMultipartUpload so no orphaned parts remain in the bucket.
GCSDriverCancels the request and source stream, then deletes the resumable session.
AzureDriverCancels the request and source stream. Staged blocks are never committed and Azure discards them.
SupabaseDriverCancels the request and source stream, and terminates an unfinished TUS upload.
CloudinaryDriverAborts 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.

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.
  • maxSize defaults to the driver's maxSizeBytes. If the driver has no limit, maxSize is required.
  • The body is counted as it arrives, so a missing or false Content-Length cannot exceed the limit (413).
  • The upload runs through client.upload: your middleware, plugins and events all apply. The response is 201 with { id, path, size }.
  • For browsers on another origin, list it in links.cors.
  • link.path is where the file will be stored, so you can save it before the upload happens.

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 goYour app, then the providerStraight to the provider
Needslinks in the client configA driver that supports it, with signing credentials
Middleware, plugins, upload eventRunSkipped (only creating the link is logged, as a getPresignedUrl event)
Size limitEnforced while streamingEnforced by the provider (S3, Google Cloud); not enforced on Azure
  • Which one you get: direct: true asks for a direct link and direct: false for one through your app. Without direct, links go through your app when links is 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 exact size, when given) through the x-goog-content-length-range header in link.headers. Send every header in link.headers as is. It needs credentials or serviceAccount.
  • 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 needs accountKey. 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 PUT from your site's origin with the headers in link.headers (content-type, plus x-goog-content-length-range on Google Cloud and x-ms-blob-type on Azure). Set it in the provider's console or CLI.
  • Checking support in code: a driver that can issue direct links sets driver.capabilities.directUpload to { 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 one id (generated, or yours via options.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 of driver.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
}
DrivercompletependingNotes
S3DriverHEAD on the objectOpen multipart upload for the keyToken stored as x-amz-meta-fileway-upload-token
GCSDriverObject metadata GETNot availableToken stored as custom metadata fileway-upload-token
AzureDriverHEAD on the blobBlocks staged but not committedToken stored as x-ms-meta-fileway_upload_token
SupabaseDriverGET /object/infoNot availableToken stored in user metadata
LocalDriverstat on the fileA .partial file is still being writtenWrites to a temp file and renames it into place, so a failed retry never damages a finished file. No token; recovery checks size
CloudinaryDriverAdmin API resource lookupNot availableToken stored in context. Public IDs are <folder>/<id> (or <id> on dynamic-folder accounts)

Future: async producers (planned). streamFactory is currently sync-only: it must return the stream directly. An async (Promise-returning) variant is a planned enhancement, which would let you pass sources like fetch(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 as new Blob([bytes]).stream() in browsers/edge/Workers, or Deno.open(path).readable in Deno.

Was this page helpful?

On this page