English
File uploads
This guide covers receiving, validating and sending files:
- Reading files
- MultipartFile
- Validation
- Serving uploaded files
- Testing uploads
- Sending files
Ream parses multipart/form-data requests through the BodyParser middleware and exposes uploaded files on the request object as MultipartFile instances. You read a file, validate it against a size and extension allowlist, then move it to disk.
Reading files
Use request.file(field, options?) for a single upload and request.files(field, options?) for multiple uploads under the same field.
typescript
const avatar = request.file('avatar') // MultipartFile | null
const photos = request.files('photos') // MultipartFile[]Uploads are nested by field name the same way form fields are. An input named documents[] is read with request.files('documents'), and one named user[avatar] with request.file('user.avatar'). When a path holds several files, request.file() returns the first one. request.allFiles() returns the whole tree, for example { documents: [file, file], user: { avatar: file } }.
request.file() returns null when no file was sent for that field, so always guard before using it.
MultipartFile
Every uploaded file is a MultipartFile with the following properties:
| Property | Description |
|---|---|
clientName | The original filename from the client — untrusted. |
size | Size in bytes. |
content | The file contents as a Buffer. |
extname | The extension DETECTED from the file's magic bytes when detectable, otherwise derived from clientName. |
detectedType | A trustworthy MIME type inferred from the magic bytes, or undefined for text formats that have no magic signature. |
mime | The full mime to validate against — image/png. Read from the magic bytes. |
type | The PRIMARY mime type — image for image/png. Same trustworthy source. |
subtype | The mime subtype — png for image/png. |
headers | The part's headers. Rust forwards only content-type today. |
fieldName | The form field the file was sent under. |
errors | Validation errors collected for this file. |
isValid | true when no validation errors are present. |
hasErrors | The inverse of isValid. |
isMultipartFile | Always true — tells a file apart from a plain field. |
state | idle, streaming, consumed or moved. |
filePath / fileName | Where the file went, once it has been moved. |
sizeLimit / allowedExtensions | Rules a bare validate() will apply. |
type changed meaning in 0.2.0
It used to hold the whole image/png; it now holds image, with subtype alongside. TypeScript cannot catch this — a comparison like file.type === 'image/png' does not fail to compile, it simply never matches again. Search your code for it, and use file.mime for an allowlist.
An app hit exactly this: if (!ALLOWED_MIME.has(file.type)) reject() compiled, stopped matching, and every avatar upload died in silence because no test covered the case that must PASS. A validation gate with no passing-case test is a gate that can close on its own.
These read the bytes, not the header
mime, type and subtype are derived from the file's magic bytes, falling back to the Content-Type header only for content that has no signature (text formats). That precedence is the one that matters: the header is written by the client, so a .exe announced as image/png would otherwise walk through a mime allowlist. A renamed file reports what it actually is. The header as sent is still on file.headers['content-type'].
And the following methods:
| Method | Description |
|---|---|
validate({ size?, extnames? }) | Re-run validation. Called bare, it uses sizeLimit / allowedExtensions. |
move(location, { name?, overwrite? }) | Persist the file to the local directory location. Creates the directory; without name the file gets a random name carrying the detected extension; overwrites by default, and overwrite: false refuses an existing file atomically. |
markAsMoved(fileName, filePath) | Record a move you performed yourself. |
stream() | Get a readable stream of the file contents. |
move() refuses any name that is not a plain filename — no separators, no . or ... The footgun it exists for is await file.move(dir, { name: file.clientName }), where a client name of ../../etc/passwd would otherwise walk out of the directory.
MultipartFile is macroable: a package can add methods to every upload at boot. That is where moveToDisk(key, disk?, options?) comes from — it is @c9up/archive's macro, attached by its provider, and does not exist without it. It writes the upload into a configured disk (the default one, or the disk named by disk) under a normalised key, streams it by default (moveAs: 'buffer' writes it in one call), accepts the disk's write options (visibility, contentType, cacheControl, contentDisposition), sets file.meta.url when the disk can name a URL, and marks the file as moved under its key. A key that climbs out of the disk is refused before anything is written. See Archive.
typescript
await request.file('avatar')?.moveToDisk(`avatars/${user.id}.png`)
await request.file('invoice')?.moveToDisk('invoices/a.pdf', 's3', { visibility: 'private' })No temporary file
Ream holds the bytes in memory — multipart.tmpDir is refused at construction — so move() writes the buffer. There is no E_MISSING_FILE_TMP_PATH here: there is no temporary file to be missing.
Validation
Pass constraints directly to request.file() to validate as you read:
typescript
const avatar = request.file('avatar', { size: '2mb', extnames: ['jpg', 'png'] })extnames is validated against the magic-byte-DETECTED type, not the client filename. A binary renamed evil.png is therefore caught. Ream reads the signature itself, with no dependency: it recognises the same formats, under the same extensions and MIME types, as the file-type library — images, audio and video containers, PDF, Office and OpenDocument files, archives, fonts and executables.
Detection reads the first 64 KiB of each file only. The files of one request also share one bound on the ZIP work (4096 entries and 4 MiB scanned): a ZIP-based file past it is not recognised, and keeps the extension the client sent (file.typeSource === 'claimed'). The body parser hands the event loop back between two files, so a request with many files does not hold the others.
The canonical controller guard checks all three failure modes:
typescript
const file = request.file('document', { size: '5mb', extnames: ['pdf', 'docx'] })
if (!file) return response.unprocessableEntity('No file uploaded')
if (file.hasErrors) return response.unprocessableEntity(file.errors)
if (file.size === 0) return response.unprocessableEntity('Uploaded file is empty')TIP
Rejecting empty (0-byte) uploads is an app-level decision (422). Ream does not auto-reject them, so add the file.size === 0 check yourself when an empty file is meaningless to your handler.
Serving uploaded files
Security
Never use the header the client sent (file.headers['content-type']) as the response Content-Type, and never trust it for application logic — file.mime (read from the bytes) is the trustworthy value, and file.typeSource === 'detected' tells you the bytes were actually recognised.
When serving user-uploaded files:
- Always send
X-Content-Type-Options: nosniffand respond with a MIME type from your own allowlist. - Remember that SVG is a text format: magic-byte detection CANNOT catch a malicious SVG renamed
.png. Serving such a file inline can execute embedded scripts (SVG-XSS).
Defend at the serving layer with one or more of:
Content-Disposition: attachmentto force a download instead of inline rendering,- a
Content-Security-Policy: sandboxheader on file responses, - or, strongest, serving user files from a separate origin / sandbox domain.
Testing uploads
The test RequestBuilder from @c9up/ream/testing builds multipart requests with .file() and .field(). .field() adds a multipart field and is distinct from .form(), which sends a url-encoded body.
typescript
const res = await client
.post('/documents')
.file('document', pngBuffer, { filename: 'a.png', contentType: 'image/png' })
.field('title', 'Hello')
.send().file(field, Buffer | string, { filename?, contentType? }) attaches the file part; pass a Buffer for binary fixtures or a string for text.
Sending files
response.download(path) and response.attachment(path, name) send a file, and response.stream(readable) sends anything else that streams.
Chunks go to the socket as they are read — nothing bigger than one chunk is ever held, so a file's size stops being the process's memory ceiling:
typescript
router.get('/exports/:id', async ({ response, params }) => {
response.header('content-type', 'text/csv')
await response.stream(createReadStream(exportPath(params.id)))
})
router.get('/invoices/:id', ({ response, params }) => {
response.attachment(invoicePath(params.id), 'invoice.pdf')
})A missing file still answers 404: download() stats it before a single header goes out, because once a stream starts there is no status left to change. Asking for an ETag (download(path, true)) buffers instead — a hash needs the whole file — so leave it off for anything large.
If the client disconnects, the source stops being read: a whole file is not pumped into a socket nobody is on.
The ceiling on a buffered body
Some bodies are not streamed: response.send(buffer), a JSON payload, an ETag'd download, or a stream() on a host with no streaming backend (a unit test, a mock server). Those are held whole in memory and base64-encoded on the way across the NAPI boundary — roughly 2.3x their size in transient memory.
Over the ceiling they throw E_RESPONSE_TOO_LARGE rather than growing until the process dies:
typescript
// 100MB by default.
{ maxResponseBytes: 100 * 1024 * 1024 }A streamed body never assembles, so the ceiling does not apply to it.
Or skip the server entirely
For files an app merely stores and serves back, a signed URL from @c9up/archive is better than either path: the client fetches straight from storage and the bytes never pass through the server at all.
Next steps
- Configuration — register middleware and wire paths
- Atlas (ORM) — persist file metadata alongside your entities