Receiving Image Uploads
Learning Objectives
- You can receive bounded multipart uploads and distinguish file bytes from metadata.
- You can design storage and serving paths without trusting a submitted filename.
- You can await one byte write before reporting that receipt has completed.
Until now, most request bodies have been small JSON objects. An upload introduces a different kind of input: bytes whose size, format, ownership, and storage lifetime matter.
Selecting portrait.png in a profile form lets the browser preview the file
immediately. A later visit needs the server to retain it and identify who may
read it. We will follow those bytes through receipt, storage and display.
The same principles apply to other attachments, but different formats need different policies. A small application can use one immutable image per resource: once accepted, those bytes cannot be replaced. We begin with receipt and validation, then connect accepted bytes to metadata and later display.
Multipart requests and bounded file receipt
A multipart request places form fields and file bytes in separate body
sections. The browser chooses a boundary, a separator used to identify those
sections, and includes it in the Content-Type header. FormData, introduced
with forms in Part 4, can carry a selected File as well as text fields:
const body = new FormData();body.set("avatar", selectedFile);const response = await fetch("/api/profile/avatar", { method: "POST", body, credentials: "include", headers: { "X-CSRF-Token": csrfToken },});Here selectedFile comes from a file input and csrfToken comes from the session flow already taught. Let the browser set the multipart Content-Type, including the boundary needed to parse the body.
The server needs a bound on the request before parsing its multipart body. Hono’s
body limit enforces that bound; the handler then checks the selected file.
The exercise configures its imports. For a local copy, hono/body-limit resolves
through this prefix in deno.json’s imports object, using the same version as
its hono mapping:
"hono/": "npm:/hono@4.13.5/"This route bounds the multipart body, then checks the file’s size:
import { bodyLimit } from "hono/body-limit";
const MAX_FILE_BYTES = 2 * 1024 * 1024;app.post( "/api/profile/avatar", bodyLimit({ maxSize: MAX_FILE_BYTES + 64 * 1024 }), async (c) => { // Session, CSRF, and ownership middleware must run before storage work. const form = await c.req.formData(); const file = form.get("avatar"); if (!(file instanceof File) || file.size === 0 || file.size > MAX_FILE_BYTES) { return c.json({ error: "INVALID_FILE" }, 400); } const bytes = new Uint8Array(await file.arrayBuffer()); // Apply the validated-format and storage steps described below. return c.json({ receivedBytes: bytes.byteLength }, 200); },);file.type is its claimed media type, such as image/png, and file.size is its
byte count. await file.arrayBuffer() reads the contents; Uint8Array lets you
inspect each byte as a number from 0 to 255, for example bytes[0]. Part 5 used
that byte-array type for password hashes. Here it is used for the uploaded file.
This handler reports the received byte count. The body limit includes a bounded allowance for multipart fields as well as the file itself. Reverse proxies and hosting platforms may impose their own limits, while this handler still needs a policy for the input it accepts.
Declared media types and file signatures
After checking the size, we still need to identify the file’s format. The
filename and media type (also called the MIME type) come from the caller.
An extension such as .png does not establish that bytes are a safe PNG. A
file signature is an expected sequence of initial bytes. The exercise gives
these values in hexadecimal; JavaScript writes such numbers with 0x, so 0x89
is the same number as decimal 137. Compare each required byte and reject a file
shorter than the signature. Production image handling should also validate
decoding, dimensions, and resource limits with a maintained library or service.
Do not accept SVG or HTML merely because it can be displayed as an image; active content has different serving risks. A small image-upload example can restrict the accepted set to PNG/JPEG and state the limits of its validation. The OWASP file-upload guidance describes layered defenses rather than a single reliable filename test.
Storage keys, adapters and metadata
Never join an untrusted filename directly onto a filesystem path. Generate a key and keep the original name as non-authoritative display metadata only when needed:
const storageKey = crypto.randomUUID();A storage adapter implements the operations that save, retrieve and remove bytes. It can map the generated key to a file inside a fixed private directory. The rest of the application calls this interface without choosing filesystem paths:
export type ObjectStorage = { put(key: string, bytes: Uint8Array): Promise<void>; get(key: string): Promise<Uint8Array | null>; remove(key: string): Promise<void>;};Image metadata is a database record linking stored bytes to ownership, validated media type, byte length, storage key and creation time. The row need not contain the binary data itself.
The production adapter decides where bytes live and how long they remain available. Local files need a persistent volume. A hosted process filesystem may not retain files after restart or share them between instances, so deployment needs a deliberate storage choice.
Receive one bounded image
The next exercise isolates receipt: validate the file, allocate one generated
key, write the original bytes once, and await that write before returning its
metadata. It supplies the File API and injected storage.
The same receipt rules apply to listing images in the next chapter. Its service
starts from independent files: a supplied validator checks the file, and
storeImage coordinates the byte write and metadata commit.
Receive a bounded avatar
0 / 25 points
Files and environment
Edit receive-avatar.ts in the editor below.
The grader supplies Deno 2 and @std/assert. The tests supply the injected
dependencies.
Task
Complete receiveAvatar(file, storage, makeKey), returning
Promise<{key:string,mediaType:string,byteLength:number}> after storage succeeds.
file is a File or null; storage.put(key, bytes) writes bytes asynchronously.
makeKey() returns a trusted generated key. It must be called once per accepted file.
Accept nonempty PNG/JPEG files up to and including 2 * 1024 * 1024 bytes. The declared
MIME type and signature must agree: image/png begins with hexadecimal
89 50 4e 47 0d 0a 1a 0a; image/jpeg begins with ff d8 ff. Every byte of
the corresponding signature must be present and match.
Throw Error("Invalid avatar") for missing, empty, oversized,
disallowed, or mismatched input before generating a key or writing anything.
For accepted input, write the original bytes once using only makeKey() for the key;
ignore the submitted filename, including path-like names. Await the write, then return
its metadata. A storage error propagates unchanged, with no retry.
The checks supply File objects in Deno.
The specified signatures define this exercise’s limited validation policy.
Complete image decoding and production image safety are outside its scope.
Check and submit
Choose Submit solution to run the checks and read their feedback. Keep the specified paths and exports. Accepted signatures/generated keys and the exact size limit are worth 5 points each; rejecting invalid input before effects is worth 10 points, and awaited storage/failure behavior 5. Check names identify the behavior to revisit.
You can now reject invalid bytes before allocating a key or writing anything. An accepted result confirms the byte write. The next chapter adds application identity, ownership and read permissions.
Check Your Understanding
- Why should the browser choose the multipart boundary?
- What do the byte-count and signature checks establish, and what do they leave outside this example’s validation policy?
- Why must a submitted filename never choose the storage path?
- Why should the function await storage before returning accepted metadata?