File Uploads & Images
By the end of this lesson a librarian can open a book in LibTrack, choose a cover image and watch a progress bar fill while it uploads. The Express API accepts only one image of up to 1 MB, checks the file's real bytes instead of trusting its name, saves it under a random name and serves it back so Angular can show it. Along the way you will meet two integration traps that only appear when the two halves meet: a security header that blocks the image, and a progress bar that never moves.
What you should know first: Login, Interceptors & Protected Routes, because only librarians may upload, and Routing & Route Guards, which built the book detail page. Multer itself is introduced in File Uploads in the Node.js course. Versions used: multer 2.5.0, @types/multer 2.3.0, Express 5.3.0, Helmet 8.3.0, Angular 22.2.6 and Node.js 26.13.1. All output is from real runs.
The plan
JSON cannot carry a file well, so browsers send uploads as multipart/form-data: one request body split into parts, each with its own headers, like a parcel with several labelled packets inside. Express's express.json() ignores such bodies. Multer is the standard Express middleware that reads them.
| Piece | Where | Job |
|---|---|---|
cover field on the book | Mongoose model and shared/api-types.ts | Stores the file name, or null |
PUT /api/books/:id/cover | routes/books.ts | Librarians only; replaces the cover |
middleware/uploads.ts | server | Size limit, byte check, random name, save and delete |
/api/covers/<name> | app.ts | Serves the saved images |
BooksApi.uploadCover() | client | Sends FormData and reports progress |
Cover section on BookDetail | client | File input, progress bar, errors, image |
Why PUT and not POST? Each book has exactly one cover. Sending a new one replaces it at the same address, which is what PUT means, as the CRUD lesson explained.
Step 1: install multer and extend the contract
In server/:
npm install multer
npm install --save-dev @types/multerUse multer 2.x. Version 1.x had denial-of-service bugs and is no longer safe. Add one field to the book schema in server/src/models/book.ts:
cover: { type: String, default: null }, // file name in uploads/covers, or nullAnd one field to Book in shared/api-types.ts:
cover: string | null; // image file name, served at /api/covers/<cover>The API stores and sends only the file name, never a full URL. The API's address differs between development and production, and the client already knows it as environment.apiUrl. Add uploads/ to libtrack/.gitignore: user files never belong in Git.
Step 2: the upload middleware
Create server/src/middleware/uploads.ts:
import { randomUUID } from "node:crypto";
import { mkdir, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import multer from "multer";
import { ApiError } from "./errors.ts";
// Covers are saved here and served at /api/covers/<file name>.
export const COVERS_DIR = path.resolve(import.meta.dirname, "../../uploads/covers");
// Keep the file in memory (max 1 MB) so we can check its real bytes before saving.
export const coverUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 1024 * 1024, files: 1, fields: 0 },
});
// The first bytes of each allowed image type, its "magic number".
const SIGNATURES = [
{ ext: "jpg", test: (b: Buffer) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
{ ext: "png", test: (b: Buffer) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) },
{ ext: "webp", test: (b: Buffer) => b.toString("latin1", 0, 4) === "RIFF" && b.toString("latin1", 8, 12) === "WEBP" },
];
// Checks the bytes, then writes the file under a new random name. Returns that name.
export async function saveCover(file: Express.Multer.File | undefined): Promise<string> {
if (!file) throw new ApiError(400, "NO_FILE", "Choose an image to upload", [{ field: "cover", message: "Choose an image" }]);
const type = SIGNATURES.find((s) => s.test(file.buffer));
if (!type) {
throw new ApiError(415, "UNSUPPORTED_IMAGE", "Covers must be JPEG, PNG or WebP images", [
{ field: "cover", message: "Use a JPEG, PNG or WebP image" },
]);
}
await mkdir(COVERS_DIR, { recursive: true });
const name = `${randomUUID()}.${type.ext}`;
await writeFile(path.join(COVERS_DIR, name), file.buffer);
return name;
}
export async function deleteCover(name: string | null | undefined) {
if (!name) return;
await unlink(path.join(COVERS_DIR, path.basename(name))).catch(() => {});
}Each choice closes a door that attackers like:
limits. At most one file of 1 MB, and no text fields at all. Without limits, one request could fill the server's memory or disk.- Memory storage. The file stays in
req.file.bufferuntil it passes the checks, so nothing untrusted touches the disk. This is safe only because the limit is small. - Magic numbers, not names. The file name (
notes.jpg) and theContent-Type(image/jpeg) are typed by the client and prove nothing. The first bytes of a real PNG are always89 50 4E 47 0D 0A 1A 0A; a JPEG startsFF D8 FF. Checking them is like checking the hologram on an Aadhaar card instead of reading the name printed on the cover. - A random name from
randomUUID(). The user's file name is never used, so names such as../../server.tsorindex.htmlcannot overwrite anything, and the extension comes from the real type. - SVG is not allowed. An SVG image can contain scripts, so accepting it would invite stored XSS.
Step 3: the route, the static folder and the errors
Add the route to server/src/routes/books.ts (and import coverUpload, saveCover and deleteCover):
// PUT /api/books/:id/cover with a multipart body that has one file in the "cover" field.
booksRouter.put("/:id/cover", requireAuth, librarianOnly, coverUpload.single("cover"), async (req, res) => {
const book = await findBook(req.params.id);
const oldCover = book.cover;
book.cover = await saveCover(req.file);
await book.save();
await deleteCover(oldCover);
res.json(book);
});Order matters: requireAuth and librarianOnly run before multer, so a stranger's upload is refused before the server reads a single byte of the body. single("cover") accepts one file from the field named cover. The old file is deleted only after the new name is saved, so a failure never leaves a book pointing at a missing image. Also add await deleteCover(book.cover); after book.deleteOne() in the delete route, so deleted books leave no orphan files.
In server/src/app.ts, serve the folder and change one Helmet option (import COVERS_DIR from the uploads file):
// "same-site" lets the Angular app on localhost:4200 show images from localhost:3000.
app.use(helmet({ crossOriginResourcePolicy: { policy: "same-site" } }));
app.use("/api/covers", express.static(COVERS_DIR, { index: false, maxAge: "7d", immutable: true }));express.static() sends files from one folder and refuses paths that climb out of it. Because every new cover gets a new name, browsers may cache each file for a week without ever showing a stale cover. The Helmet change is explained in Step 6.
Finally, teach toApiError() in middleware/errors.ts about multer's own errors (import multer from "multer";):
if (err instanceof multer.MulterError) {
const tooBig = err.code === "LIMIT_FILE_SIZE";
return new ApiError(tooBig ? 413 : 400, tooBig ? "FILE_TOO_LARGE" : "BAD_UPLOAD",
tooBig ? "The image is larger than 1 MB" : "The upload could not be read",
[{ field: err.field ?? "cover", message: tooBig ? "Use an image of 1 MB or less" : err.message }]);
}If you wrote requireJson in the error-handling exercise, it checks only POST and PATCH, so this multipart PUT passes through it.
Step 4: test the route with curl
curl's -F option builds a multipart body; ;type= lets us lie about the type on purpose. We logged in as Priya and Meera first, as in the JWT lesson, and used four test files: a 2.8 KB PNG, a text file renamed notes.jpg, a 1.4 MB PNG and the right PNG under the wrong field name.
curl -i -X PUT http://localhost:3000/api/books/$GODAN/cover -F "cover=@godan-cover.png"
curl -i -b priya.txt -X PUT http://localhost:3000/api/books/$GODAN/cover -F "cover=@godan-cover.png"
curl -i -b meera.txt -X PUT http://localhost:3000/api/books/$GODAN/cover -F "cover=@godan-cover.png"
curl -i -b meera.txt -X PUT http://localhost:3000/api/books/$GODAN/cover -F "cover=@notes.jpg;type=image/jpeg"
curl -i -b meera.txt -X PUT http://localhost:3000/api/books/$GODAN/cover -F "cover=@big-scan.png"
curl -i -b meera.txt -X PUT http://localhost:3000/api/books/$GODAN/cover -F "photo=@godan-cover.png"HTTP/1.1 401 Unauthorized
{"error":{"code":"NOT_LOGGED_IN","message":"Please log in"}}
HTTP/1.1 403 Forbidden
{"error":{"code":"FORBIDDEN","message":"You do not have permission to do this"}}
HTTP/1.1 200 OK
{"title":"Godan","author":"Premchand","isbn":"9789300000011","category":"Literature","copies":4,"available":3,"cover":"d74b6100-2cfb-49bf-8907-922b522e627a.png","createdAt":"2026-11-16T13:54:33.904Z","updatedAt":"2026-11-16T13:54:42.956Z","id":"6afb0b19176f0588c4dad74f"}
HTTP/1.1 415 Unsupported Media Type
{"error":{"code":"UNSUPPORTED_IMAGE","message":"Covers must be JPEG, PNG or WebP images","details":[{"field":"cover","message":"Use a JPEG, PNG or WebP image"}]}}
HTTP/1.1 413 Payload Too Large
{"error":{"code":"FILE_TOO_LARGE","message":"The image is larger than 1 MB","details":[{"field":"cover","message":"Use an image of 1 MB or less"}]}}
HTTP/1.1 400 Bad Request
{"error":{"code":"BAD_UPLOAD","message":"The upload could not be read","details":[{"field":"photo","message":"Unexpected file field"}]}}Only status lines and bodies are shown (curl also printed HTTP/1.1 100 Continue before the 413). Every failure uses the standard error shape. The text file was refused although it claimed to be image/jpeg. Then we fetched the saved image:
HTTP/1.1 200 OK Cross-Origin-Resource-Policy: same-site X-Content-Type-Options: nosniff Cache-Control: public, max-age=604800, immutable Content-Type: image/png Content-Length: 2853
X-Content-Type-Options: nosniff (from Helmet) tells the browser to trust the Content-Type and never guess, which is another guard against files pretending to be something else.
Step 5: upload from Angular with progress
Add two methods to BooksApi:
// Sends the image as multipart/form-data and reports progress events while it uploads.
uploadCover(id: string, file: File): Observable<HttpEvent<Book>> {
const body = new FormData();
body.append('cover', file); // the field name multer expects: coverUpload.single("cover")
return this.http.put<Book>(`${this.url}/${id}/cover`, body, { reportProgress: true, observe: 'events' });
}
// Covers are served by the API, so their address starts with apiUrl too.
coverUrl(book: Book): string | null {
return book.cover ? `${environment.apiUrl}/covers/${book.cover}` : null;
}Do not set a Content-Type header yourself. For a FormData body the browser writes multipart/form-data plus a boundary, the marker that separates the parts; a hand-written header has no boundary, and multer cannot read the body. observe: 'events' returns every stage of the request instead of only the final body, and reportProgress: true adds progress events.
In BookDetail, add a computed image address, two signals and a handler:
protected readonly coverSrc = computed(() => (this.book.hasValue() ? this.api.coverUrl(this.book.value()) : null));
protected readonly progress = signal<number | null>(null); // 0-100 while uploading
protected readonly uploadError = signal('');
protected uploadCover(input: HTMLInputElement) {
const file = input.files?.[0];
input.value = ''; // so choosing the same file again fires (change) again
if (!file) return;
// A quick check for the user's comfort. The server checks the real bytes again.
if (file.size > 1024 * 1024) {
this.uploadError.set('Choose an image of 1 MB or less.');
return;
}
this.uploadError.set('');
this.progress.set(0);
this.api.uploadCover(this.id(), file).subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress) {
this.progress.set(Math.round((100 * event.loaded) / (event.total ?? file.size)));
} else if (event.type === HttpEventType.Response && event.body) {
this.book.value.set(event.body); // show the new cover without reloading
this.progress.set(null);
}
},
error: (err) => {
this.uploadError.set(apiErrorMessage(err));
this.progress.set(null);
},
});
}And in the template, for librarians only:
@if (auth.isLibrarian() && book.hasValue()) {
<section aria-labelledby="cover-heading">
<h3 id="cover-heading">Cover image</h3>
<label for="cover">JPEG, PNG or WebP, up to 1 MB</label>
<input id="cover" #file type="file" accept="image/jpeg,image/png,image/webp"
[disabled]="progress() !== null" (change)="uploadCover(file)" />
@if (progress() !== null) {
<p><progress max="100" [value]="progress()"></progress> {{ progress() }}%</p>
}
@if (uploadError()) {
<p class="error" role="alert">{{ uploadError() }}</p>
}
</section>
}Above the book's details, show <img [src]="src" [alt]="'Cover of ' + b.title" width="160" /> inside @if (coverSrc(); as src). The accept attribute only filters the file picker; it is a hint, not a check.
Step 6: two traps, seen in a real browser
We logged in as Meera in headless Chrome and opened Godan, which already had the cover from the curl test.
Trap 1: the image does not show. With plain helmet(), the image box stayed empty and Chrome's console said:
image: Cover of Godan: 0x0 log.error: Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin
Helmet's default Cross-Origin-Resource-Policy: same-origin lets only pages from localhost:3000 itself use the API's files. The app lives on localhost:4200, a different origin. The two are the same site, though, because a site ignores the port. With policy: "same-site" the image loaded at once (400x600). In production, with the app and /api on one domain, either value works; same-site still blocks other websites from embedding your covers.
Trap 2: the progress bar never moves. To see progress on a fast computer, we told Chrome to limit uploads to 256 KB per second, like a weak college Wi-Fi, and uploaded a 720 KB PNG. The first try printed:
progress text seen: 0% -> done
Angular 22's HttpClient uses the fetch() API by default, and fetch cannot report upload progress. The Angular API docs say so for withFetch(), and suggest withXhr(), which uses XMLHttpRequest, for upload progress. Change one line in app.config.ts:
// withXhr(): the default fetch backend cannot report upload progress.
provideHttpClient(withXhr(), withInterceptors([authInterceptor])),The same upload then printed, with the API's log underneath:
progress text seen: 9% -> 20% -> 34% -> 45% -> 57% -> 70% -> 77% -> 89% -> done image: Cover of Godan: 400x600 notes.jpg: Covers must be JPEG, PNG or WebP images big-scan.png: Choose an image of 1 MB or less. PUT /api/books/6afb0b19176f0588c4dad74f/cover 200 2871ms GET /api/covers/042a5b2e-d0a2-428a-913c-bd9e1114dab1.png 200 291ms PUT /api/books/6afb0b19176f0588c4dad74f/cover 415 21ms
The fake notes.jpg reached the server and was refused by the byte check. The 1.4 MB file never left the browser, because the client-side size check stopped it first. The interceptor from the last lesson added the login cookie to the upload as well. Only one cover file was left on disk afterwards: the route deleted each replaced file.
Peek at a file's first bytes
This page runs the same magic-number check in the browser on three built-in samples. You can also choose any file from your computer to see its first bytes; nothing is uploaded.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Magic numbers</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>What is this file, really?</h1>
<label for="pick">Choose a file (optional)</label>
<input id="pick" type="file">
<pre id="out"></pre>
<script>
const signatures = [
{ type: "JPEG", test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff },
{ type: "PNG", test: (b) => [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((x, i) => b[i] === x) },
{ type: "WebP", test: (b) => String.fromCharCode(...b.slice(0, 4)) === "RIFF" && String.fromCharCode(...b.slice(8, 12)) === "WEBP" },
];
const hex = (b) => [...b.slice(0, 12)].map((x) => x.toString(16).padStart(2, "0")).join(" ");
const sniff = (b) => (signatures.find((s) => s.test(b)) || { type: "not an allowed image" }).type;
const samples = {
"godan-cover.png": new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13]),
"photo.jpg": new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1]),
"notes.jpg": new TextEncoder().encode("These are my exam notes"),
};
const lines = [];
for (const [name, bytes] of Object.entries(samples)) {
lines.push(name.padEnd(16) + hex(bytes) + " -> " + sniff(bytes));
}
document.querySelector("#out").textContent = lines.join("\n");
console.log(lines);
document.querySelector("#pick").addEventListener("change", async (e) => {
const file = e.target.files[0];
if (!file) return;
const bytes = new Uint8Array(await file.slice(0, 12).arrayBuffer());
lines.push(file.name.padEnd(16) + hex(bytes) + " -> " + sniff(bytes) + " (" + file.size + " bytes)");
document.querySelector("#out").textContent = lines.join("\n");
});
</script>
</body>
</html>The first two samples are recognised as PNG and JPEG. notes.jpg starts with the letters "Thes" (54 68 65 73), so it is "not an allowed image", whatever its name says. Choose a real photo and then rename a text file to .png to compare.
Common mistakes
- Trusting the file name or
Content-Type. Both are typed by the client. Check the bytes. - Saving with the user's file name. Use a random name and pick the extension yourself.
- No
limitsin multer. One huge upload can fill memory or disk. - Setting
Content-TypeforFormDataby hand. The boundary goes missing and multer cannot read the body. - Expecting upload progress with the default fetch backend. Add
withXhr()for upload progress. - Forgetting
Cross-Origin-Resource-Policywhen the app and the API are on different origins. The browser blocks the image even though the request succeeded. - Accepting SVG as an image. SVG files can carry scripts.
Interview questions
1. Why check an upload's magic number instead of its extension or MIME type?
The file name and the Content-Type of each part are chosen by the client, so an attacker can label any file as image/jpeg. The first bytes of a real file follow its format, so checking them shows what the file really is. It is still wise to limit the size and save under a server-chosen name.
2. When would you use multer's memory storage instead of disk storage?
Memory storage keeps the file in a buffer, which is convenient for small files that you want to check, resize or send to cloud storage before anything is written. For large files it would use too much memory, so disk storage into a temporary folder, with strict size limits, is better there.
3. How do you show upload progress with Angular's HttpClient?
Send the request with reportProgress: true and observe: 'events', then handle HttpEventType.UploadProgress events using loaded and total. In Angular 22 the default backend uses fetch, which cannot report upload progress, so the app must use provideHttpClient(withXhr()).
4. Why does the cover route run requireAuth before multer?
Middleware runs in order. Checking the login first means the server rejects strangers before it reads and buffers the request body, which saves memory and blocks a simple denial-of-service trick.
Key points
- Uploads travel as
multipart/form-data; multer 2 reads them, here withmemoryStorage()and a 1 MB limit. saveCover()checks the magic number, saves under a random name and returns only the name.- The cover route is
PUT /api/books/:id/cover, guarded byrequireAuthandlibrarianOnlybefore multer. - Images are served from
/api/coverswithexpress.static; Helmet'ssame-siteresource policy lets the app show them. - Multer errors become 413 or 400 in the standard error shape; fake images get 415.
- Angular sends
FormDatawithreportProgressandobserve: 'events', and needswithXhr()for upload progress.
Exercise
Add a "Remove cover" button for librarians on the book detail page. On the server, write DELETE /api/books/:id/cover (librarians only) that deletes the file, sets cover back to null and returns the book. In Angular, add BooksApi.removeCover(id) and update the page with the returned book. What should happen if the book has no cover?
Show solution
// server/src/routes/books.ts
booksRouter.delete("/:id/cover", requireAuth, librarianOnly, async (req, res) => {
const book = await findBook(req.params.id);
const oldCover = book.cover;
book.cover = null;
await book.save();
await deleteCover(oldCover);
res.json(book);
});
// client: books-api.ts
removeCover(id: string): Observable<Book> {
return this.http.delete<Book>(`${this.url}/${id}/cover`);
}
// client: book-detail.ts
protected removeCover() {
this.api.removeCover(this.id()).subscribe({
next: (book) => this.book.value.set(book),
error: (err) => this.uploadError.set(apiErrorMessage(err)),
});
}Show the button only inside @if (coverSrc()). If the book has no cover, the route still answers 200 with cover: null: removing something that is already gone is harmless, so the request is safe to repeat. This route returns the book rather than 204 because the page needs the updated object.
Quick Quiz
1. A user uploads notes.txt renamed to notes.jpg with Content-Type: image/jpeg. What does LibTrack answer?
The byte check ignores the name and the claimed type.
2. Why does the Angular app need withXhr() for the cover upload?
Fetch can send the file, but only XHR gives upload progress events.
3. The image request succeeds but Chrome shows ERR_BLOCKED_BY_RESPONSE.NotSameOrigin. What should you change?
Helmet's default same-origin policy blocks the API's files on pages from another origin.
4. Why is requireAuth placed before coverUpload.single("cover")?
Middleware runs in order; checking login first avoids buffering uploads from unknown users.
Learn MEAN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
