EthicsComputerCourses
Join training +91 90532 10052

File Uploads & Images

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

By the end of this lesson each NoteNest note can carry one image, such as a photo of a whiteboard or a scanned hall ticket. The server will accept only real JPEG, PNG or WebP files up to 2 MB, store them under random names in a folder the web server never serves directly, and send each image only to the note's owner. On the Vue side you will build an upload box with an instant preview.

What you should know first: Forms, Login & Protected Routes, because uploads need a logged-in user, and Error Handling & Middleware for the error classes. The Node.js course covers uploads on their own in File Uploads. Versions checked: multer 2.5.0 with Express 5.3.0, Mongoose 9.12.1 and Vue 3.5.

Why uploads are a risky feature

An upload carries bytes Zod cannot check, a file name chosen by the user, and a type label that the browser (or an attacker's script) made up. Things that go wrong in real apps:

RiskWhat an attacker triesNoteNest's defence
Huge filesFill the disk or memory with a 2 GB "photo"fileSize limit of 2 MB
Fake typesA script renamed photo.pngCheck the first bytes of the file
Dangerous typesAn SVG with <script> insideAllow only JPEG, PNG and WebP
Path tricksA file named ../../src/app.jsIgnore the user's name; use a random one
Public foldersGuess /uploads/aadhaar.jpg and download itStore outside any public folder; serve through a route that checks the owner

Think of a railway cloakroom. The attendant checks your bag, puts it on a numbered shelf behind the counter and gives you a token. Nobody walks into the back room, and the bag comes back only to the right token.

The plan

One image per note, replaced or removed as a whole, so the routes are:

Method and pathBodySuccess
PUT /api/notes/:id/imagemultipart/form-data, field image200 { note }
GET /api/notes/:id/imagenone200 with the image bytes
DELETE /api/notes/:id/imagenone204

Files are sent as multipart/form-data, the encoding HTML forms use for files: the body is split into parts, each with its own headers. express.json() cannot read it, so we need multer, the Express team's middleware for multipart bodies. All three routes sit inside the notes router, so requireAuth and the owner check already apply.

Step 1: Configure multer

Install it in server/:

Terminal
npm install multer

Create server/src/middleware/upload.js:

JavaScript
// server/src/middleware/upload.js
import multer from 'multer'
import { ValidationError } from '../errors.js'

export const MAX_IMAGE_BYTES = 2 * 1024 * 1024 // 2 MB

// The only types we accept, and the extension we save each one with.
export const IMAGE_TYPES = new Map([
  ['image/jpeg', '.jpg'],
  ['image/png', '.png'],
  ['image/webp', '.webp'],
])

export const uploadImage = multer({
  storage: multer.memoryStorage(), // keep the bytes in req.file.buffer until we have checked them
  limits: { fileSize: MAX_IMAGE_BYTES, files: 1, fields: 0 },
  fileFilter(req, file, cb) {
    if (IMAGE_TYPES.has(file.mimetype)) return cb(null, true)
    cb(new ValidationError('Only JPEG, PNG or WebP images are allowed'))
  },
}).single('image')

// Reads the first bytes of the file. The browser's mimetype is only a claim.
export function detectImageType(buffer) {
  if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) {
    return 'image/jpeg'
  }
  if (buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
    return 'image/png'
  }
  if (buffer.toString('latin1', 0, 4) === 'RIFF' && buffer.toString('latin1', 8, 12) === 'WEBP') {
    return 'image/webp'
  }
  return null
}

Line by line:

  • memoryStorage() keeps the upload in a Buffer until the route has checked it, which the 2 MB limit keeps safe. For large files such as videos, use diskStorage or stream to cloud storage instead.
  • limits are the main defence against abuse. fileSize stops reading after 2 MB, files: 1 refuses a second file, and fields: 0 refuses extra text fields, because this route expects nothing else.
  • fileFilter rejects unwanted types early, but file.mimetype comes from the client, so it is only a first filter.
  • .single('image') accepts exactly one file in the field named image, and puts it in req.file.
  • detectImageType checks the magic bytes: the fixed signature at the start of each format. Every PNG starts with the bytes 89 50 4E 47 0D 0A 1A 0A, every JPEG with FF D8 FF, and WebP with RIFF and then WEBP at byte 8. A text file renamed .png fails this check. The file-type package covers many more formats.

SVG is left out on purpose. An SVG is XML and may contain <script>. If the browser opens it directly, that script runs on your origin, which is a stored XSS bug.

Step 2: Save files outside the web root

The web root is any folder whose files a server hands out as they are, such as client/public or a folder given to express.static(). Uploaded files must never go there, or anyone could fetch them by URL and skip the owner check. Add one setting to config.js:

JavaScript
// server/src/config.js (new lines)
import path from 'node:path'

// inside the config object:
uploadDir: path.resolve(process.env.UPLOAD_DIR ?? 'uploads'),

By default that is server/uploads, which no route serves. Add uploads/ to the root .gitignore and UPLOAD_DIR=./uploads to .env.example. In production, point UPLOAD_DIR at a folder that survives redeploys and is backed up. Then a small helper file, server/src/images.js:

JavaScript
// server/src/images.js
import { randomUUID } from 'node:crypto'
import fs from 'node:fs/promises'
import path from 'node:path'
import { config } from './config.js'
import { IMAGE_TYPES } from './middleware/upload.js'

// Saves the bytes under a name we choose, never the name the user sent.
export async function saveImage(buffer, mimeType) {
  const filename = `${randomUUID()}${IMAGE_TYPES.get(mimeType)}`
  await fs.mkdir(config.uploadDir, { recursive: true })
  await fs.writeFile(path.join(config.uploadDir, filename), buffer, { flag: 'wx' })
  return filename
}

export async function removeImage(filename) {
  if (filename) await fs.rm(path.join(config.uploadDir, filename), { force: true })
}

The name is a random UUID plus an extension that comes from the detected type, so a user can never choose the name, the folder or the extension. flag: 'wx' refuses to overwrite an existing file.

Step 3: Store the image details on the note

Add an image sub-document to the Note schema, and keep the file name out of the JSON:

JavaScript
// server/src/models/Note.js (changed parts)
image: {
  type: new mongoose.Schema(
    { filename: String, mimeType: String, size: Number, uploadedAt: Date },
    { _id: false },
  ),
  default: null,
},

// in toJSON:
const { _id, owner, image, ...rest } = ret
return {
  id: _id.toString(),
  ...rest,
  // The client learns the size and date, never the file name on disk.
  image: image ? { mimeType: image.mimeType, size: image.size, uploadedAt: image.uploadedAt } : null,
}

The database stores the file's name and facts, not the bytes, which keeps documents small and files easy to back up or move to object storage later.

Step 4: The three routes

Add these to routes/notes.js, importing uploadImage, detectImageType, saveImage, removeImage, config and ValidationError:

JavaScript
// server/src/routes/notes.js (new routes)
// PUT /api/notes/:id/image (multipart form, field "image")
router.put('/:id/image', uploadImage, async (req, res) => {
  const note = await findNote(req.params.id, req.userId)
  if (!req.file) throw new ValidationError('Choose an image to upload')
  const realType = detectImageType(req.file.buffer)
  if (!realType) throw new ValidationError('That file is not a real JPEG, PNG or WebP image')

  const oldFilename = note.image?.filename
  const filename = await saveImage(req.file.buffer, realType)
  note.image = { filename, mimeType: realType, size: req.file.size, uploadedAt: new Date() }
  await note.save()
  await removeImage(oldFilename)
  res.json({ note })
})

// GET /api/notes/:id/image (only the owner can see it)
router.get('/:id/image', async (req, res) => {
  const note = await findNote(req.params.id, req.userId)
  if (!note.image) throw new NotFoundError('This note has no image')
  res.sendFile(note.image.filename, {
    root: config.uploadDir,
    cacheControl: false,
    headers: {
      'Content-Type': note.image.mimeType,
      'Cache-Control': 'private, max-age=3600',
    },
  })
})

// DELETE /api/notes/:id/image
router.delete('/:id/image', async (req, res) => {
  const note = await findNote(req.params.id, req.userId)
  const oldFilename = note.image?.filename
  note.image = null
  await note.save()
  await removeImage(oldFilename)
  res.status(204).end()
})

Also add await removeImage(note.image?.filename) after note.deleteOne() in the existing DELETE /:id route, so deleting a note deletes its file. The new file is saved before the old one is removed, so a failed save never leaves a note pointing at nothing.

findNote is the same owner-checking helper as before, so Rohan gets a 404 for Priya's image. sendFile with root refuses any path that climbs out of that folder. Cache-Control: private lets the browser cache the image but tells shared caches, such as an office proxy, not to keep a copy.

Finally, teach the error handler about multer's own errors in middleware/errors.js:

JavaScript
// server/src/middleware/errors.js (inside toAppError, before the body-parser checks)
if (err instanceof multer.MulterError) {
  if (err.code === 'LIMIT_FILE_SIZE') return new AppError(413, 'FILE_TOO_LARGE', 'Image can be at most 2 MB')
  return new BadRequestError('Send one image in the "image" field')
}

Step 5: Try it with curl

curl's -F sends a multipart form; @ reads a file. We logged in as Priya (cookie in jar.txt) and as Rohan (rjar.txt) and made test files: a real 240 by 160 PNG, a text file named notes.png, an SVG containing a script and a 3 MB fake photo. Real responses, numbered in order:

Terminal
curl -b jar.txt -X PUT http://localhost:3000/api/notes/6afaad197d5bd8f5d73091b1/image -F "image=@syllabus.png"
Output
{"note":{"id":"6afaad197d5bd8f5d73091b1","title":"DBMS viva questions","body":"Normal forms, keys, ACID","tags":["college"],"pinned":true,"createdAt":"2026-11-16T07:13:29.861Z","updatedAt":"2026-11-16T08:19:01.211Z","image":{"mimeType":"image/png","size":765,"uploadedAt":"2026-11-16T08:19:01.183Z"}}}

Then curl -i on the GET route, keeping the useful headers. Cross-Origin-Resource-Policy and nosniff come from Helmet:

Output
HTTP/1.1 200 OK
Cross-Origin-Resource-Policy: same-origin
X-Content-Type-Options: nosniff
Content-Type: image/png
Cache-Control: private, max-age=3600
Content-Length: 765

Next: Rohan asking for the image, no cookie at all, the renamed text file sent with type=image/png, the SVG, the 3 MB file, the file in a field called photo, and the PNG with an extra text field:

Output
{"error":{"code":"NOT_FOUND","message":"Note not found"}}
{"error":{"code":"UNAUTHORIZED","message":"Please log in"}}
{"error":{"code":"VALIDATION_ERROR","message":"That file is not a real JPEG, PNG or WebP image"}}
{"error":{"code":"VALIDATION_ERROR","message":"Only JPEG, PNG or WebP images are allowed"}}
{"error":{"code":"FILE_TOO_LARGE","message":"Image can be at most 2 MB"}}
{"error":{"code":"BAD_REQUEST","message":"Send one image in the \"image\" field"}}
{"error":{"code":"BAD_REQUEST","message":"Send one image in the \"image\" field"}}

The 3 MB upload came back with status 413 Payload Too Large. Last, we uploaded the PNG again with the file name ../../server/src/app.js. It succeeded, and the uploads folder held one file with a random name; the old image had been removed:

Output
afbd8110-ae1b-4291-891f-1f2800e2ee2f.png

Step 6: Upload and preview in Vue

apiRequest always sets Content-Type: application/json. For a FormData body that is wrong: the browser must write the multipart header itself, because it includes a random boundary string that separates the parts. Change two lines in client/src/api/client.js (and export BASE_URL, which noteImageUrl below needs):

JavaScript
// client/src/api/client.js (inside apiRequest)
// FormData sets its own multipart Content-Type (with the boundary), so leave it alone.
const isForm = options.body instanceof FormData
// ...and in the fetch options:
headers: isForm ? options.headers : { 'Content-Type': 'application/json', ...options.headers },

Add three functions to api/notes.js:

JavaScript
// client/src/api/notes.js (new functions; also import BASE_URL from './client.js')
export function uploadNoteImage(id, file) {
  const form = new FormData()
  form.append('image', file)
  return apiRequest(`/notes/${encodeURIComponent(id)}/image`, { method: 'PUT', body: form })
}

export function deleteNoteImage(id) {
  return apiRequest(`/notes/${encodeURIComponent(id)}/image`, { method: 'DELETE' })
}

// The upload time in the URL makes the browser fetch a new copy after a change.
export function noteImageUrl(note) {
  const version = Date.parse(note.image.uploadedAt)
  return `${BASE_URL}/notes/${encodeURIComponent(note.id)}/image?v=${version}`
}

An <img> request to /api/... carries the login cookie by itself, because the cookie's path is /api and the image is on the same site. The ?v= part changes after every upload, so a cached old image is never shown.

Now client/src/components/NoteImage.vue. Its key part is the preview: URL.createObjectURL(file) gives a temporary blob: address for a file that is still on the user's computer, so the image shows before any upload.

HTML
<!-- client/src/components/NoteImage.vue (script setup, main parts) -->
<script setup>
import { ref, watch, onWatcherCleanup } from 'vue'
import { uploadNoteImage, deleteNoteImage, noteImageUrl } from '@/api/notes.js'

const props = defineProps({ note: { type: Object, required: true } })
const emit = defineEmits(['updated'])

const MAX_BYTES = 2 * 1024 * 1024
const TYPES = ['image/jpeg', 'image/png', 'image/webp']
const file = ref(null)
const previewUrl = ref('')
const problem = ref('')
const busy = ref(false)

// Make a temporary blob: URL for the chosen file, and free it when the file changes.
watch(file, (chosen) => {
  previewUrl.value = ''
  if (!chosen) return
  const url = URL.createObjectURL(chosen)
  previewUrl.value = url
  onWatcherCleanup(() => URL.revokeObjectURL(url))
})

function choose(event) {
  const chosen = event.target.files[0] ?? null
  problem.value = ''
  if (chosen && !TYPES.includes(chosen.type)) {
    problem.value = 'Choose a JPEG, PNG or WebP image.'
  } else if (chosen && chosen.size > MAX_BYTES) {
    problem.value = `This image is ${(chosen.size / 1024 / 1024).toFixed(1)} MB. The limit is 2 MB.`
  }
  file.value = problem.value ? null : chosen
  if (problem.value) event.target.value = '' // clear the input
}

async function upload() {
  busy.value = true
  problem.value = ''
  try {
    const data = await uploadNoteImage(props.note.id, file.value)
    emit('updated', data.note)
    file.value = null
  } catch (err) {
    problem.value = err.message // the server's message, for example the 2 MB limit
  } finally {
    busy.value = false
  }
}
// remove() calls deleteNoteImage and emits the note with image: null
</script>

The template shows the preview if there is one, otherwise the saved image with :src="noteImageUrl(note)" and an alt such as "Image attached to Sunday groceries", then an <input type="file" accept="image/jpeg,image/png,image/webp">, the problem message with role="alert", and Upload or Remove buttons. accept only filters the file picker, and the client checks are only for quick feedback. revokeObjectURL frees the memory a blob: URL holds.

Place <NoteImage :note="note" @updated="onUpdated" /> in NoteDetailView.vue, where onUpdated sets note.value and copies the new data into the store's cached note with Object.assign, so the list stays in step.

We tested it in headless Chrome as Priya on "Sunday groceries". Choosing a 4 MB file showed This image is 4.0 MB. The limit is 2 MB. without any request. Choosing the PNG showed a preview from a blob:http://localhost:5245/... address, 240 pixels wide. After Upload, the image came from the API instead:

Output
[["/api/notes/6afaad197d5bd8f5d73091b2/image?v=1794817220567",240,"Image attached to Sunday groceries"]]

Check a file in the browser

The page below runs the same checks a user's browser can do before uploading: type, size and the magic bytes, read with file.slice(0, 12).arrayBuffer(). Pick any file from your computer.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Image check and preview</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-width: 30rem; }
    img { max-width: 100%; border-radius: 8px; outline: 3px dashed #42b883; margin-top: 8px; }
    .bad { color: #b00020; }
    .good { color: #1b6e3c; }
    code { background: #f4f4f4; padding: 0 4px; }
  </style>
</head>
<body>
  <div id="app">
    <h1>Attach an image</h1>
    <label for="file">Image (JPEG, PNG or WebP, up to 2 MB)</label><br>
    <input id="file" type="file" accept="image/jpeg,image/png,image/webp" @change="choose">
    <ul v-if="report">
      <li>Name sent by the browser: <code>{{ report.name }}</code></li>
      <li>Type claimed: <code>{{ report.claimed || '(none)' }}</code></li>
      <li>Type from magic bytes: <code>{{ report.real || 'unknown' }}</code></li>
      <li>Size: {{ report.sizeText }}</li>
    </ul>
    <p v-if="problem" class="bad" role="alert">{{ problem }}</p>
    <p v-else-if="report" class="good">This file would be accepted.</p>
    <img v-if="previewUrl" :src="previewUrl" alt="Preview of the chosen image">
  </div>

  <script>
    const MAX_BYTES = 2 * 1024 * 1024;

    // Same signatures as detectImageType on the server
    function detect(bytes) {
      const text = (from, to) => String.fromCharCode(...bytes.slice(from, to));
      if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg";
      if ([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((b, i) => bytes[i] === b)) return "image/png";
      if (text(0, 4) === "RIFF" && text(8, 12) === "WEBP") return "image/webp";
      return null;
    }

    Vue.createApp({
      data: () => ({ report: null, problem: "", previewUrl: "" }),
      methods: {
        async choose(event) {
          const file = event.target.files[0];
          if (this.previewUrl) URL.revokeObjectURL(this.previewUrl);
          this.previewUrl = "";
          this.problem = "";
          this.report = null;
          if (!file) return;
          const bytes = new Uint8Array(await file.slice(0, 12).arrayBuffer());
          const real = detect(bytes);
          this.report = {
            name: file.name, claimed: file.type, real,
            sizeText: new Intl.NumberFormat("en-IN").format(file.size) + " bytes"
          };
          if (!real) this.problem = "That file is not a real JPEG, PNG or WebP image.";
          else if (file.size > MAX_BYTES) this.problem = "Image can be at most 2 MB.";
          else this.previewUrl = URL.createObjectURL(file);
        }
      }
    }).mount("#app");
  </script>
</body>
</html>

Rename a text file to test.png and pick it (choose "All files" in the picker): the claimed type is image/png, but the magic bytes say unknown.

Common mistakes

  • Trusting file.mimetype or the extension. Both come from the client. Check the magic bytes.
  • Saving uploads in public/ or a static folder. Anyone with the URL can download them, logged in or not.
  • No size limit. One request can fill the server's memory or disk. Always set limits.fileSize.
  • Setting Content-Type by hand for FormData. The boundary goes missing and multer cannot parse the body. Let the browser set it.

Interview questions

1. Why is checking the MIME type that the browser sends not enough?

The Content-Type of each part and the file extension are both chosen by the client, so an attacker can label any file image/png. The server should read the file's magic bytes, or decode the image, to learn its real type, and only then accept it.

2. Why store uploads outside the web root?

Files in a public folder are served to anyone who knows or guesses the URL, skipping login and ownership checks. Storing them elsewhere and serving them through a route lets the app check permissions on every request and set safe headers.

3. How do you make sure an updated image is not shown from the browser cache?

Change the URL when the content changes, for example by adding a version such as the upload time (?v=1794817220567). The browser treats it as a new resource, while unchanged images can still be cached.

Key points

  • multer parses multipart/form-data; .single('image') with limits (fileSize, files, fields) and a fileFilter stops most abuse early.
  • The server checks magic bytes, because the client's type label and extension can lie; SVG is not accepted.
  • Files get random UUID names and live in UPLOAD_DIR, outside any public folder and outside Git.
  • The note stores the file's facts; toJSON hides the disk name; GET /api/notes/:id/image uses the owner check and sendFile with root.
  • Replacing or deleting an image, or deleting the note, removes the old file.
  • In Vue, send FormData without a manual Content-Type, preview with URL.createObjectURL and revoke it, and add ?v= to bust the cache.

Exercise

Rohan wants to see how much space his images use. Add GET /api/auth/me/storage that returns { "count": 2, "bytes": 1530, "readable": "1.5 KB" } for the logged-in user, using the image.size values already stored on his notes (no reading from disk). Then add a rule to the upload route: a user may store at most 20 MB of images in total; a new upload that would go over the limit returns 413 with the code QUOTA_EXCEEDED.

Show solution

A MongoDB aggregation adds up the sizes without loading every note:

JavaScript
// server/src/routes/auth.js
import mongoose from 'mongoose'
import { Note } from '../models/Note.js'

async function imageUsage(userId) {
  const [row] = await Note.aggregate([
    { $match: { owner: new mongoose.Types.ObjectId(userId), image: { $ne: null } } },
    { $group: { _id: null, count: { $sum: 1 }, bytes: { $sum: '$image.size' } } },
  ])
  return { count: row?.count ?? 0, bytes: row?.bytes ?? 0 }
}

router.get('/me/storage', requireAuth, async (req, res) => {
  const { count, bytes } = await imageUsage(req.userId)
  res.json({ count, bytes, readable: `${(bytes / 1024).toFixed(1)} KB` })
})

Export imageUsage (or move it to images.js) and use it in the upload route, after the magic-byte check:

JavaScript
const { bytes } = await imageUsage(req.userId)
const freed = note.image?.size ?? 0 // replacing an image frees its old size
if (bytes - freed + req.file.size > 20 * 1024 * 1024) {
  throw new AppError(413, 'QUOTA_EXCEEDED', 'You can store at most 20 MB of images')
}

aggregate does not cast values the way find does, so the owner id is converted to an ObjectId by hand.

Quick Quiz

1. A user uploads a text file renamed to notes.png with the type image/png. Which NoteNest check rejects it?

2. Why does NoteNest save uploads as random UUID names?

3. What is wrong with setting headers: { 'Content-Type': 'multipart/form-data' } for a FormData upload?

4. Rohan requests GET /api/notes/<Priya's note id>/image. What does he get?

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