File Upload
elements man recipes/file-uploadUser picks one or more files in a form. The browser reads the bytes and an RPC
stores them. A route serves the bytes back so an <img src> can display them.
Store the bytes in Postgres or in S3 or any object store. Both are supported,
and both serve from every app server: the form, the File[] binding and the
RPC are the same either way, and only the insert and the serve route change.
This page stores files in a Postgres bytea column; "Object storage" below
shows the object store version.
The <input type="file" value={files}> binding reads each picked file's bytes
into the bound field. The
form's submit handler waits for any in-flight file reads to finish before it
runs, so there is no race between picking a file and submitting.
Binding one file or several
The multiple attribute decides the type the input binds:
Inputs<input type="file" value={avatar}> <!-- one File --> <input type="file" multiple value={photos}> <!-- a File[] -->
Bound fieldsprivate avatar: File; // no multiple private photos: File[] = []; // multiple
The build reports an error when the field's type does not match the input. File[] on an input without multiple
is an error, and so is a single File on one with it.
The FileUpload (opens in a new tab) template from @elements/ui,
which every new app has (elements man ui), wraps the same input in a drop
zone with a file list and previews. It always binds files as a File[];
maxFiles={1} is the one-file case, and the file is files[0].
The rest of this page builds a gallery with FileUpload and File[]. For a
single attachment on a bare input, drop multiple and use File wherever you
see File[].
Migration
Scaffold with elements create migration, then add the columns specific to file
storage.
Terminalelements create migration 'add images' -tables=images
app/migrations/<timestamp>-add-images.migration.sql-- add images -- Auto-update updatedAt on row changes. create or replace function touchUpdatedAt() returns trigger language plpgsql as $$ begin new.updatedAt = now(); return new; end; $$; create table images ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), updatedAt timestamptz not null default now(), name text not null, contentType text not null, size integer not null, data bytea not null ); create trigger imagesTouchUpdatedAt before update on images for each row execute function touchUpdatedAt();
The four columns added to the scaffold's table are name, contentType, size,
and data. The data column is bytea. File.data (a Uint8Array)
interpolates into a bytea parameter directly.
Gallery services
Terminalelements create page gallery
That writes
app/pages/gallery/{index.ts, template.ehtml, style.css, test.ts}. The
ImageMeta interface and the upload rpc go in template.ehtml, and the route
imports them from there.
app/pages/gallery/template.ehtml, above the markup:
app/pages/gallery/template.ehtmlimport "./style.css"; import { sql, tx, File, ValidationError } from "@elements/app"; import { Button } from "@elements/ui/button"; import { FileUpload } from "@elements/ui/file-upload"; // The types this gallery is willing to store and later serve inline. Anything // not on this list is rejected. See "Never trust the uploaded content type". const ALLOWED = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]); export interface ImageMeta { id: string; name: string; contentType: string; size: number; createdAt: Date; } /** @rpc */ export function upload(files: File[]): ImageMeta[] { for (let f of files) { if (!ALLOWED.has(f.contentType)) { throw new ValidationError(`${f.name} is not an image`); } } tx(() => { for (let f of files) { sql( ` insert into images ( name, contentType, size, data ) values ( ${f.name}, ${f.contentType}, ${f.size}, ${f.data} ) `, ); } }); return sql<ImageMeta>(` select id, name, contentType, size, createdAt from images order by createdAt desc `).all(); }
The allowlist runs before tx() so a rejected file fails the whole batch before
anything is written. The bulk insert then runs inside tx() so the batch is
atomic: if one row fails, none commit. The RPC returns the refreshed metadata
list; the template reassigns its parameter and the grid re-renders.
This gallery uploads files only, so File[] is its own parameter. A form that
also collects text (a post with a title, a body, and an attachment) puts the
File[] in the same form object as the other fields and passes that one object
to a single @rpc, rather than splitting files into a separate parameter:
PostForminterface PostForm { title: string; body: string; files: File[]; } /** @rpc */ export function createPost(form: PostForm): Post { // form.files is a File[] like any other field }
PostForm input<input type="file" multiple value={form.files}>
File[] is sent to an RPC inside a form object exactly as it is on its
own. A single File field works the same way:
ProfileForminterface ProfileForm { name: string; avatar: File; }
ProfileForm input<input type="file" value={form.avatar}>
Gallery route
app/pages/gallery/index.tsimport { Request, Response, sql } from "@elements/app"; import gallery, { ImageMeta } from "./template"; export default function route(req: Request, res: Response) { let images = sql<ImageMeta>(` select id, name, contentType, size, createdAt from images order by createdAt desc `).all(); return new gallery({ initial: images }); }
The select lists every column except data so the metadata stays small.
Pulling every image's bytes into the HTML render would put megabytes of base64
in the response. The bytes are served separately, on demand, by the route below.
Gallery template
The rest of app/pages/gallery/template.ehtml, under the code above:
app/pages/gallery/template.ehtmlinterface Gallery { images: ImageMeta[]; files: File[]; } function onSubmit(gallery: Gallery) { gallery.images = upload(gallery.files); gallery.files = []; } <html class="page-gallery" ( initial: ImageMeta[], private gallery: Gallery = { images: initial, files: [], }, )> <main class="page-shell"> <form class="stack" onsubmit={() => onSubmit(gallery)}> <FileUpload files={gallery.files} accept="image/*" maxFiles={20} /> <Button type="submit" variant="primary">upload</Button> </form> <ul class="gallery"> <li e:for={img of gallery.images}> <img src={`/images/${img.id}`} alt={img.name}> <span>{img.name}</span> </li> </ul> </main> </html>
files={gallery.files} binds the FileUpload to a File[] field. The user
drops, pastes or browses for files; the template reads each file's bytes,
lists it with a preview and its size, and assigns the array. accept filters
the picker and maxFiles caps a batch. On submit, onSubmit calls
upload(...), and the RPC's return value replaces gallery.images, which
re-renders the grid. Setting gallery.files = [] after the RPC resolves
clears the list via the same binding so the form is ready for the next batch.
The submit is a Button (opens in a new tab).
The two fields are one object because onSubmit reassigns both. An object
passes to onSubmit by reference, so when the handler sets one of its fields
the template renders again. With images as its own attribute, an
assignment to it inside a function would change only the function's
parameter
(elements man html/reactivity). The route passes its rows as initial, which is
the first value of gallery.images.
Serving the bytes
The serve route returns binary bytes, not HTML, so it isn't a page. Create the file by hand alongside the pages.
app/routes/images.tsimport { Request, Response, sql } from "@elements/app"; export interface Image { id: string; name: string; contentType: string; data: Buffer; } const INLINE = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]); export default function serveImage(req: Request, res: Response) { let img = sql<Image>(` select id, name, contentType, data from images where id = ${req.params.id} `).firstOrThrow(); if (INLINE.has(img.contentType)) { res.setHeader("Content-Type", img.contentType); } else { // Not a type we are willing to render on our own origin. Send it as an // opaque download instead of letting the browser decide what it is. res.setHeader("Content-Type", "application/octet-stream"); res.setHeader("Content-Disposition", "attachment"); } return img.data; }
firstOrThrow() returns a safe 404 if the id doesn't exist. Returning a Buffer
sends its bytes as the response body, with no EJSON serialization.
Never trust the uploaded content type
The allowlist appears twice on purpose: once in the upload RPC and once in
the serve route. The check in the serve route sets the Content-Type the
browser receives.
f.contentType is supplied by whoever uploaded the file. It is not derived from
the bytes. If you store it and echo it back, someone uploads a file declaring
text/html, your serve route answers with Content-Type: text/html, and the
browser runs their markup on your origin, with your origin's full
privileges, including the signed-in user's session. The serve route decides
the content type, never the uploader.
Checking on upload is necessary but not sufficient: rows can predate the check,
arrive from a migration, or be written by another code path. The serve route is
the only code that sets the Content-Type header, so it checks the allowlist
too.
Two more protections:
- Elements sends
X-Content-Type-Options: nosniffon every response, so a file whose declared type isimage/pngbut whose bytes are HTML is not reinterpreted. The allowlist and the header work together: the allowlist controls the type the route declares, andnosniffstops the browser from treating the bytes as any other type. - For anything beyond images, serve user content from a different origin. A separate hostname keeps user content away from your session cookie.
How large a file can be
The files travel inside the rpc message, base64 encoded, and an rpc message
is capped by server.maxUpload in config.jsoc, 25 MB by default. That
leaves room for about 18 MB of files per call. A call over the cap fails in the
browser with "Request too large". Raise the cap for a few larger images; for
video, or anything that can run to hundreds of megabytes, upload directly to
object storage, below.
Object storage
For a bucket you already run, install an S3 client with elements install and
keep the images table as metadata plus the object key:
- Replace the
data byteacolumn withobjectKey text not null. - In
upload, write eachf.datato the bucket under a new key, then insert the row with that key. - In the serve route, read the row, fetch the object by its key, and return
its bytes with the same
INLINEcheck.
The allowlist, the gallery route and the template stay exactly as they are.
Large files: upload directly to storage
The browser uploads video and other large files directly to the bucket, so the bytes are never sent to the app server. One RPC runs before the upload and one after it:
createUpload({ name, size, contentType })checks the type and size, inserts a row marked pending, and returns a presigned PUT url for a new key (getSignedUrlwith aPutObjectCommand, from@aws-sdk/s3-request-presigner).- The browser PUTs the bytes to that url with the same
Content-Type.XMLHttpRequestrather thanfetch, for itsupload.onprogress. finishUpload(id)reads the object back withHeadObjectCommand, checks its size and type against the row, and marks the row ready.
Browser sidelet created = createUpload({ name: f.name, size: f.size, contentType: f.contentType }); let xhr = new XMLHttpRequest(); xhr.open("PUT", created.putUrl); xhr.setRequestHeader("Content-Type", f.contentType); xhr.upload.onprogress = (e) => showProgress(e.loaded / e.total); xhr.onload = () => finishUpload(created.id); xhr.send(new Blob([f.data], { type: f.contentType }));
Create the S3 client with requestChecksumCalculation: "WHEN_REQUIRED": the
default adds a checksum header to the presigned url that a browser cannot
send, and S3 refuses the PUT. The bucket needs a CORS rule allowing PUT from
the app's origin. Serve the file from a presigned GET or the bucket's own
url, and keep the INLINE rule: set the object's ContentType from your
allowlist, never from the upload.
Routes
Register both routes in index.ts:
index.tsimport gallery from "#app/pages/gallery"; import serveImage from "#app/routes/images"; // ... app.route("/gallery", gallery); app.route("/images/:id", serveImage);
Notes
File.datais aUint8Arrayon the browser. The RPC receives the same bytes on the server, decoded by the Elements JSON deserializer.${f.data}is passed to the query as thebyteaparameter.- The metadata query in the route handler omits
dataon purpose. Selecting*would pull every image's bytes into the HTML render, which is usually megabytes of base64 you don't need. accept="image/*"is a hint to the file picker, not a server-side check. The allowlist in the RPC is the check.