EthicsComputerCourses
Join training +91 90532 10052

File Uploads & Images

MERN Stack · Lesson 14 of 20 Intermediate 13 min read Updated

By the end of this lesson a teacher can attach a photo of a worksheet or a PDF timetable to a task, see image thumbnails on the task page, and download any attachment. Behind that simple feature you will build the safe version: a size limit, a type check on the file's real bytes, random names on disk, storage that the web server never serves directly, and a download route that checks the login cookie first.

What you should know first: Login, Protected Routes & Sessions, because uploads and downloads need a signed-in user. Multer itself, multipart forms and disk storage are explained in File Uploads in the Node.js course; this lesson connects them to TaskBoard's models, permissions and React pages. Versions checked: multer 2.5.0, file-type 22.3.0, Express 5.3.0 and Mongoose 9.12.1. Every output below comes from a real run.

Why uploads need extra care

A file is the most dangerous input a server accepts. A JSON title is at most a few hundred characters, but a file can be 2 GB, can claim to be a photo while holding a script, and can arrive with a name such as ../../server/src/app.js.

Think of the parcel counter at a railway station. The clerk weighs every parcel, checks what is really inside whatever the label says, sticks on the railway's own tag number, keeps it in a locked store room, and hands it over only against a valid receipt. TaskBoard does the same:

RiskWhat could happenTaskBoard's answer
Huge filesMemory or disk fills up, server stopslimits.fileSize of 2 MB, one file per request
Fake typesAn HTML or SVG file with a script is served as a "photo"file-type reads the first bytes; only PNG, JPEG, WebP, PDF
Dangerous names../ in a name writes outside the folderWe choose the name: a random UUID plus the detected extension
Public folderAnyone with the URL downloads private filesFiles live in server/uploads, never under express.static
Open downloadsFormer staff keep accessDownload route sits behind requireAuth

Step 1: Install and configure

From the top folder:

Terminal
npm install multer file-type -w server

Multer is Express middleware that reads multipart/form-data, the request format browsers use for files. Version 2 fixed denial-of-service bugs found in 1.x, so never use 1.x. file-type detects a file's real type from its magic number, the first few bytes that every format starts with. A PNG always begins with the bytes 89 50 4E 47 and a PDF with %PDF. file-type 22 is an ES module only, which suits TaskBoard.

Add the folder to server/src/config.js:

JavaScript
import path from "node:path";
// ... inside the config object:
  // Outside client/ and never served by express.static: files leave only through the download route.
  uploadDir: path.resolve(import.meta.dirname, "..", process.env.UPLOAD_DIR ?? "uploads"),

import.meta.dirname is the folder of config.js, so the default is always server/uploads. In server.js, after connectDB, add await fs.mkdir(config.uploadDir, { recursive: true }); (with import fs from "node:fs/promises";) so the folder exists. Add server/uploads/ to .gitignore: uploaded files are user data, not source code. Add UPLOAD_DIR=uploads to .env.example so teammates see the setting.

Step 2: Attachments on the Task model

The bytes go on disk; MongoDB stores a small record about each file. A task has only a few attachments, which are always shown with the task, so they are embedded as an array of subdocuments. In server/src/models/Task.js:

JavaScript
// One uploaded file. The bytes live on disk; this records where and what.
const attachmentSchema = new mongoose.Schema(
  {
    originalName: { type: String, required: true, maxlength: 100 },
    storedName: { type: String, required: true },
    mimeType: { type: String, required: true },
    size: { type: Number, required: true },
    uploadedBy: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
  },
  { timestamps: { createdAt: true, updatedAt: false }, toJSON }
);

// ...and in taskSchema:
attachments: { type: [attachmentSchema], default: [] },

storedName is our private name on disk, so clients never need it. Add delete ret.storedName; to the transform in models/toJSON.js, next to passwordHash.

Step 3: Multer with limits

Create server/src/middleware/upload.js:

JavaScript
import multer from "multer";

export const MAX_FILE_MB = 2;

// One file, field name "file", at most 2 MB, kept in memory until we have checked it.
export const uploadOneFile = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: MAX_FILE_MB * 1024 * 1024, files: 1, fields: 0 },
  defParamCharset: "utf8", // so names such as "परीक्षा-समय.pdf" arrive intact
}).single("file");

Memory storage keeps the upload in req.file.buffer instead of writing it straight to disk. That way nothing touches the disk until the type check passes. It is safe only because the limit is small: 2 MB times a few uploads at once is little memory. For large files, use multer.diskStorage into a temporary folder and check with fileTypeFromFile.

fields: 0 refuses text fields, because this route needs none. Multer reads file names as latin1 by default: in our test, परीक्षा-समय.pdf arrived as परà¥à¤...pdf. With defParamCharset: "utf8" it arrives exactly as typed.

Step 4: Check, save and record

Create server/src/controllers/attachments.controller.js. In tasks.controller.js, export findTaskOr404 and move the ownership check into an exported assertCanChange(user, task), so uploads follow exactly the same rule as edits:

JavaScript
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import { fileTypeFromBuffer } from "file-type";
import { config } from "../config.js";
import { HttpError } from "../utils/httpError.js";
import { assertCanChange, findTaskOr404 } from "./tasks.controller.js";

// Decided by the file's first bytes, never by its name or the browser's Content-Type.
const ALLOWED = new Set(["image/png", "image/jpeg", "image/webp", "application/pdf"]);
const MAX_PER_TASK = 5;

// Keeps a display name only: no folders, no control characters, at most 100 characters.
function cleanName(name) {
  const base = path.basename(name.replaceAll("\\", "/"));
  return base.replace(/[\u0000-\u001f\u007f]/g, "").slice(-100) || "file";
}

export async function addAttachment(req, res) {
  if (!req.file) {
    throw new HttpError(400, "Validation failed", [{ field: "file", message: "Choose a file to upload" }]);
  }
  const task = await findTaskOr404(req.params.id);
  assertCanChange(req.user, task);
  if (task.attachments.length >= MAX_PER_TASK) {
    throw new HttpError(409, `A task can have at most ${MAX_PER_TASK} attachments`);
  }

  const type = await fileTypeFromBuffer(req.file.buffer);
  if (!type || !ALLOWED.has(type.mime)) {
    throw new HttpError(415, "Only PNG, JPEG or WebP images and PDF files are allowed", [
      { field: "file", message: "This file type is not allowed" },
    ]);
  }

  const storedName = `${randomUUID()}.${type.ext}`; // our name, never the user's
  await fs.writeFile(path.join(config.uploadDir, storedName), req.file.buffer, { flag: "wx" });
  task.attachments.push({
    originalName: cleanName(req.file.originalname),
    storedName,
    mimeType: type.mime,
    size: req.file.size,
    uploadedBy: req.user._id,
  });
  await task.save();
  res.status(201).json(task.attachments.at(-1));
}

Notice what is not trusted: the file name (cleaned for display only), the extension, and req.file.mimetype, which is whatever the client claimed. The extension on disk comes from the detected type. flag: "wx" makes writeFile fail rather than overwrite an existing file. SVG is left out on purpose: it is an image format that can contain JavaScript. 415 Unsupported Media Type is the HTTP status for "I do not accept this kind of content".

Multer reports its own problems as a MulterError with a code. Teach the error handler about them, in translate() before the 11000 branch:

JavaScript
if (err.name === "MulterError") {
  const tooBig = err.code === "LIMIT_FILE_SIZE";
  const message = tooBig ? "File is too large (limit 2 MB)" : `Upload refused: ${err.message}`;
  return new HttpError(tooBig ? 413 : 400, message, [{ field: "file", message }]);
}

Step 5: A download route that checks the login

Add to the same controller:

JavaScript
export async function downloadAttachment(req, res) {
  const task = await findTaskOr404(req.params.id);
  const file = task.attachments.id(req.params.attachmentId);
  if (!file) throw new HttpError(404, "Attachment not found");
  res.set("Cache-Control", "private, no-store");
  // root keeps the path inside uploadDir; download() adds Content-Disposition: attachment
  res.download(file.storedName, file.originalName, { root: config.uploadDir });
}

task.attachments.id() finds a subdocument by its id. res.download() sends the file with Content-Disposition: attachment, which tells the browser to save it rather than open it as a page, and uses the original name for the saved file. The root option keeps the path inside the uploads folder. private, no-store stops shared caches from keeping a copy. Wire both routes in tasks.routes.js; the whole router already runs behind requireAuth:

JavaScript
tasksRouter.param("attachmentId", objectIdParam("Attachment"));
tasksRouter.post("/:id/attachments", uploadOneFile, addAttachment);
tasksRouter.get("/:id/attachments/:attachmentId", downloadAttachment);

When an admin deletes a task, its files should go too. In deleteTask, after the record is removed:

JavaScript
await Promise.all(task.attachments.map((a) => fs.rm(path.join(config.uploadDir, a.storedName), { force: true })));

Step 6: Try it with curl

curl -F "file=@name" sends a multipart upload, as a browser form does. Signed in as Priya, on her own task. marks.png is really a text file holding <script>alert(1)</script>, and big-scan.pdf is 3 MB:

Output
worksheet-photo.png   201 {"originalName":"worksheet-photo.png","mimeType":"image/png","size":99,"uploadedBy":"6afaf660af2c66b783a879a3","createdAt":"2026-11-16T12:26:35.985Z","id":"6afaf67b03963240891588c3"}
timetable.pdf         201 {"originalName":"timetable.pdf","mimeType":"application/pdf","size":125,...}
marks.png             415 {"error":{"message":"Only PNG, JPEG or WebP images and PDF files are allowed","details":[{"field":"file","message":"This file type is not allowed"}]}}
notes.svg             415 (same message)
big-scan.pdf          413 {"error":{"message":"File is too large (limit 2 MB)","details":[{"field":"file","message":"File is too large (limit 2 MB)"}]}}
परीक्षा-समय.pdf        201 {"originalName":"परीक्षा-समय.pdf","mimeType":"application/pdf",...}

And the requests that should fail for other reasons:

Output
timetable.pdf on Kabir's task      403 {"error":{"message":"You can only change tasks assigned to you"}}
no cookie                          401 {"error":{"message":"Please log in"}}
field named "photo"                400 {"error":{"message":"Upload refused: Unexpected file field",...}}
an extra text field                400 {"error":{"message":"Upload refused: Too many fields",...}}
no file at all                     400 {"error":{"message":"Validation failed","details":[{"field":"file","message":"Choose a file to upload"}]}}

On disk, the uploads folder held only names we chose, such as ed7e0785-0422-4d8f-ab0e-400ca62d638c.png. Kabir downloaded Priya's photo; the bytes matched the original exactly, and the headers were:

Output
HTTP/1.1 200 OK
X-Content-Type-Options: nosniff
Cache-Control: private, no-store
Content-Disposition: attachment; filename=worksheet-photo.png
Content-Type: image/png
Content-Length: 99

X-Content-Type-Options: nosniff comes from helmet; it stops the browser guessing a different type. For the Hindi name, Express also sent filename*=UTF-8''%E0%A4%AA..., the encoded form browsers use to restore it. Without a cookie, the download returned 401.

Step 7: Upload from React

apiRequest sets Content-Type: application/json and calls JSON.stringify. A file must travel as FormData instead, and the browser must set the Content-Type itself, because it includes a random boundary, the marker that separates the parts. In api/client.js:

JavaScript
// For addresses the browser loads itself, such as <img src> and download links.
export const apiUrl = (path) => BASE_URL + path;

// ...inside apiRequest:
const isForm = body instanceof FormData; // the browser sets its multipart Content-Type itself
// ...in the fetch options:
headers: body === undefined || isForm ? {} : { "Content-Type": "application/json" },
body: body === undefined || isForm ? body : JSON.stringify(body),

Then two functions in api/tasks.js:

JavaScript
export function uploadAttachment(taskId, file) {
  const form = new FormData();
  form.append("file", file);
  return apiRequest(`/api/tasks/${taskId}/attachments`, { method: "POST", body: form });
}

export function attachmentUrl(taskId, attachmentId) {
  return apiUrl(`/api/tasks/${taskId}/attachments/${attachmentId}`);
}

A new components/Attachments.jsx lists the files and shows an upload form. Its core:

React JSX
const MAX_BYTES = 2 * 1024 * 1024; // same limit as the server

async function handleSubmit(event) {
  event.preventDefault();
  const form = event.currentTarget;
  const file = form.elements.file.files[0];
  setError("");
  if (!file) return setError("Choose a file to upload");
  if (file.size > MAX_BYTES) return setError("File is too large (limit 2 MB)"); // saves a wasted upload
  setUploading(true);
  try {
    onAdded(await uploadAttachment(task.id, file));
    form.reset();
  } catch (err) {
    setError(err.message);
  } finally {
    setUploading(false);
  }
}

// in the list, images also get a thumbnail:
{a.mimeType.startsWith("image/") && (
  <img src={attachmentUrl(task.id, a.id)} alt={a.originalName} width="120" loading="lazy" />
)}
<a href={attachmentUrl(task.id, a.id)}>{a.originalName}</a>

The file input uses accept=".png,.jpg,.jpeg,.webp,.pdf", which only filters the file picker; it is a hint, not a check. TaskPage renders <Attachments> with canUpload={user.role === "admin" || task.assignee?.id === user.id}, the same rule as assertCanChange, and an onAdded that appends the new file to the task. useTask now also returns setTask for that.

In Chrome, Priya's task page showed the list with a 40 x 30 pixel thumbnail. big-scan.pdf showed "File is too large (limit 2 MB)" with no request at all; marks.png came back 415; a real PNG joined the list at once. On Kabir's task she saw no upload form. The thumbnail loads because the <img> request goes to the same origin under /api, so the cookie travels with it. Content-Disposition: attachment only affects opening the address directly, not <img>.

See what the bytes say

The buttons make three small "files". Each name says one thing; the first bytes may say another.

React JSXOpen in editor
import { useState } from "react";
import { createRoot } from "react-dom/client";

const SIGNATURES = [
  { mime: "image/png", bytes: [0x89, 0x50, 0x4e, 0x47] },
  { mime: "image/jpeg", bytes: [0xff, 0xd8, 0xff] },
  { mime: "application/pdf", bytes: [0x25, 0x50, 0x44, 0x46] }, // "%PDF"
];
const ALLOWED = new Set(["image/png", "image/jpeg", "application/pdf"]);

async function sniff(file) {
  const head = new Uint8Array(await file.slice(0, 8).arrayBuffer());
  const hex = [...head].map((b) => b.toString(16).padStart(2, "0")).join(" ");
  const found = SIGNATURES.find((s) => s.bytes.every((b, i) => head[i] === b));
  return { hex, mime: found?.mime ?? "unknown" };
}

const samples = {
  "worksheet-photo.png": new File([new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])], "worksheet-photo.png", { type: "image/png" }),
  "timetable.pdf": new File(["%PDF-1.4\n"], "timetable.pdf", { type: "application/pdf" }),
  "marks.png": new File(["<script>alert(1)"], "marks.png", { type: "image/png" }),
};

function Sniffer() {
  const [rows, setRows] = useState([]);
  async function check(file) {
    const { hex, mime } = await sniff(file);
    const verdict = ALLOWED.has(mime) ? "201 accepted" : "415 refused";
    setRows((r) => [...r.slice(-4), { name: file.name, claimed: file.type || "(none)", hex, mime, verdict }]);
  }
  return (
    <div>
      {Object.keys(samples).map((n) => <button key={n} onClick={() => check(samples[n])}>{n}</button>)}
      <p><label>Or pick your own file: <input type="file" onChange={(e) => e.target.files[0] && check(e.target.files[0])} /></label></p>
      <table>
        <thead><tr><th>Name</th><th>Browser says</th><th>First bytes</th><th>Bytes say</th><th>Server</th></tr></thead>
        <tbody>{rows.map((r, i) => <tr key={i}><td>{r.name}</td><td>{r.claimed}</td><td><code>{r.hex}</code></td><td>{r.mime}</td><td>{r.verdict}</td></tr>)}</tbody>
      </table>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<Sniffer />);

worksheet-photo.png starts with 89 50 4e 47 and is accepted. marks.png claims image/png, but its bytes start with 3c 73 63 72, the text <scr, so it is refused. Real detection libraries know hundreds of signatures; this demo knows three.

The second demo is the browser half: pick an image, see a preview before uploading, and see what FormData will send. Files over 2 MB are stopped before any upload.

React JSXOpen in editor
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";

const MAX_BYTES = 2 * 1024 * 1024;
const kb = (n) => `${new Intl.NumberFormat("en-IN").format(Math.ceil(n / 1024))} KB`;

function UploadPreview() {
  const [file, setFile] = useState(null);
  const [preview, setPreview] = useState("");

  useEffect(() => {
    if (!file || !file.type.startsWith("image/")) return;
    const url = URL.createObjectURL(file); // a blob: address that exists only in this tab
    setPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);

  const tooBig = file && file.size > MAX_BYTES;
  const form = new FormData();
  if (file) form.append("file", file);

  return (
    <div>
      <input type="file" accept=".png,.jpg,.jpeg,.webp,.pdf" onChange={(e) => { setPreview(""); setFile(e.target.files[0] ?? null); }} />
      {file && <p>{file.name}, {kb(file.size)}, browser says {file.type || "unknown"}</p>}
      {tooBig && <p role="alert" style={{ color: "crimson" }}>File is too large (limit 2 MB). Nothing was sent.</p>}
      {preview && <img src={preview} alt="Preview of the chosen file" width="160" />}
      {file && !tooBig && <p>FormData parts: {[...form.keys()].join(", ")}; ready for POST /api/tasks/:id/attachments</p>}
    </div>
  );
}

createRoot(document.getElementById("root")).render(<UploadPreview />);

Choose a photo from your computer: it appears at once, with its size in KB. Choose something larger than 2 MB and the red message appears instead. Nothing leaves your computer in this demo.

Common mistakes

  • Trusting the extension or mimetype. Both come from the client. Check the bytes.
  • No size limit. Multer's default lets a single file be as large as the client likes; always set limits.fileSize.
  • Keeping the user's file name on disk. It can contain ../, clash with another file or reveal personal data. Generate a name.
  • Serving the uploads folder statically. Every file becomes public and may run as HTML. Use an authenticated route.
  • Setting Content-Type for FormData yourself. The boundary goes missing and multer cannot read the body.
  • Deleting the record but not the file. Orphan files fill the disk; remove both together.

Interview questions

1. How do you validate the type of an uploaded file?

Do not trust the file name or the Content-Type sent by the client, because both are easy to fake. Read the first bytes of the file and match them against known signatures, for example with the file-type library, and allow only a short list of types. For images, re-encoding them with an image library is an even stronger check.

2. Why store uploads outside the public folder?

Files in a statically served folder can be fetched by anyone who knows the URL, bypassing login and permission checks. A file holding HTML or SVG might also be rendered on your domain and run scripts. Serving through a route lets you check the user and set safe headers such as Content-Disposition: attachment.

3. What does Content-Disposition: attachment do?

It tells the browser to download the response as a file instead of displaying it, and can suggest a file name. It reduces the risk of user files being rendered as pages on your site, while <img> tags can still display allowed images.

Key points

  • Multer reads multipart/form-data; set limits (size, file count, fields) and defParamCharset: "utf8" for non-English names.
  • Check the real type with file-type on the bytes; allow only PNG, JPEG, WebP and PDF; refuse SVG and HTML.
  • Save under a random UUID name in server/uploads, outside any public folder, and keep it out of Git.
  • Embed small attachment records in the task; hide storedName in JSON.
  • Upload and download routes sit behind requireAuth; uploads use the same assertCanChange rule as edits.
  • In React, send FormData without setting Content-Type; check the size first for a faster message, but rely on the server.

Exercise

Add DELETE /api/tasks/:id/attachments/:attachmentId. Only an admin or the task's assignee may delete (reuse assertCanChange). Remove the subdocument from the task, save it, and delete the file from disk. Reply 204, or 404 if the attachment does not exist. Test it with curl: delete one of Priya's files twice, then try one on Kabir's task as Priya, and count the files in server/uploads before and after.

Show solution
JavaScript
// attachments.controller.js
export async function deleteAttachment(req, res) {
  const task = await findTaskOr404(req.params.id);
  assertCanChange(req.user, task);
  const file = task.attachments.id(req.params.attachmentId);
  if (!file) throw new HttpError(404, "Attachment not found");
  file.deleteOne(); // removes the subdocument from task.attachments
  await task.save();
  await fs.rm(path.join(config.uploadDir, file.storedName), { force: true });
  res.status(204).end();
}

// tasks.routes.js
tasksRouter.delete("/:id/attachments/:attachmentId", deleteAttachment);
Output
files in uploads: 4
Priya deletes timetable.pdf on her task     204
the same request again                      404 {"error":{"message":"Attachment not found"}}
files in uploads: 3
Priya deletes a file on Kabir's task        403 {"error":{"message":"You can only change tasks assigned to you"}}

The record is saved before the file is removed. If removing the file failed, you would have a harmless orphan file rather than a record pointing at nothing. force: true means a file that is already missing does not cause an error.

Quick Quiz

1. A file named marks.png arrives with Content-Type: image/png but contains <script> text. What does TaskBoard reply?

2. Why does uploadOneFile use memoryStorage with a 2 MB limit?

3. How should React send a file to the API?

4. Which header makes the browser save a download instead of opening it as a page?

Learn MERN 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