Skip to main content

Frontend development · Intermediate · 30 min

Upload files with drag and drop and a progress bar

By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard and XMLHttpRequest · Node.js 26.13.1 LTS · checked in Chromium with Playwright 1.65.1

You will build an accessible upload field that takes picked or dropped files, checks their type and size, previews images, uploads to a small Node.js server with a progress bar and a Cancel button, and passes a Playwright test.

On this page

Most upload widgets start from a styled div that says "Drop files here" and grow outwards: a hidden input bolted on for clicks, a fetch call that shows a spinner but no progress, and no way to stop a 40 MB mistake once it starts. Keyboard users cannot reach the div, phones cannot drag anything, and the server trusts whatever the browser said the file was.

This tutorial builds it the other way round. The base is a real <input type="file">, which already works with a keyboard, a screen reader and the file or camera chooser on a phone. Drag and drop is added on top for people with a mouse. Each file is checked for type and size before a single byte is sent, images get a small preview, and the upload uses XMLHttpRequest, because it still has the one thing fetch() lacks: an event that reports how many bytes have gone up. A <progress> bar shows that, a Cancel button stops it, and a small Node.js server checks every file again, because nothing the browser checks can be trusted on its own.

The example is a "Upload documents" page that accepts PNG, JPEG and PDF files up to 5 MB each. That limit and the Cancel button matter for anyone on prepaid mobile data, common across much of Africa: a person on a low-end Android phone who picks the wrong 8 MB camera photo should hear "too large" at once, not after paying for the upload.

Step 1 · Write the page around a real file input

Make a demo folder and write the page. The upload field is a labelled <input type="file"> inside a box that will become the drop zone. The list below it will hold one row per file, and the empty paragraph with role="status" is a live region for short announcements such as "receipt.png: Uploaded".

Bash
mkdir -p ~/upload-demo
cd ~/upload-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Upload documents</title>
  <link rel="stylesheet" href="style.css">
  <script src="upload.js" defer></script>
</head>
<body>
  <main>
    <h1>Upload documents</h1>
    <div class="drop-zone">
      <label for="files">Choose files</label>
      <p id="files-hint" class="hint">PNG, JPEG or PDF, up to 5 MB each. You can also drag files into this box.</p>
      <input id="files" type="file" name="files" multiple
             accept="image/png,image/jpeg,application/pdf"
             aria-describedby="files-hint">
    </div>
    <ul id="file-list" class="file-list"></ul>
    <p id="status" class="visually-hidden" role="status"></p>
  </main>
</body>
</html>
HTML
touch upload.js

Then the styles. The native input stays visible; ::file-selector-button restyles only its button part, so it keeps its keyboard behaviour and its "No file chosen" text. The .is-over state for the drop zone changes the border from dashed to solid as well as the colour, so it does not rely on colour alone.

Bash
cd ~/upload-demo
cat > style.css <<'CSS'
:root {
  --text: #1b1f24;
  --text-muted: #5a6270;
  --surface: #ffffff;
  --canvas: #f6f7f8;
  --border: #7d8592;
  --line: #d5d9df;
  --accent: #0f5e5a;
  --accent-tint: #e3f0ee;
  --error: #a3261b;
  --done: #1f6b3a;
}
* { box-sizing: border-box; }
body {
  margin: 0;
  background: var(--canvas);
  color: var(--text);
  font-family: system-ui, sans-serif;
  line-height: 1.5;
}
main { max-width: 34rem; margin: 0 auto; padding: 1rem; }
h1 { font-size: 1.5rem; margin: 0 0 1rem; }

.drop-zone {
  padding: 1.5rem 1rem;
  border: 2px dashed var(--border);
  border-radius: 0.75rem;
  background: var(--surface);
  text-align: center;
}
.drop-zone.is-over {
  border-style: solid;
  border-color: var(--accent);
  background: var(--accent-tint);
}
.drop-zone label { display: block; font-size: 1.125rem; font-weight: 600; }
.hint { margin: 0.25rem 0 1rem; color: var(--text-muted); font-size: 0.875rem; }

input[type="file"] { max-width: 100%; font: inherit; }
input[type="file"]::file-selector-button {
  min-height: 2.75rem;
  margin-right: 0.75rem;
  padding: 0.5rem 1rem;
  border: 0;
  border-radius: 0.5rem;
  background: var(--accent);
  color: #ffffff;
  font: inherit;
  font-weight: 600;
  cursor: pointer;
}
input[type="file"]:focus-visible,
.cancel:focus-visible {
  outline: 3px solid var(--accent);
  outline-offset: 2px;
}

.file-list { display: grid; gap: 0.75rem; margin: 1.5rem 0 0; padding: 0; list-style: none; }
.file {
  display: grid;
  grid-template-columns: 3.5rem 1fr auto;
  gap: 0.75rem;
  align-items: center;
  padding: 0.75rem;
  border: 1px solid var(--line);
  border-radius: 0.75rem;
  background: var(--surface);
}
.thumb {
  display: grid;
  place-items: center;
  width: 3.5rem;
  height: 3.5rem;
  overflow: hidden;
  border-radius: 0.5rem;
  background: var(--canvas);
  color: var(--text-muted);
  font-size: 0.75rem;
  font-weight: 600;
}
.thumb img { width: 100%; height: 100%; object-fit: cover; }
.details { min-width: 0; }
.name { margin: 0; font-weight: 600; overflow-wrap: anywhere; }
.meta { margin: 0.125rem 0 0.375rem; color: var(--text-muted); font-size: 0.875rem; }
progress { width: 100%; height: 0.5rem; accent-color: var(--accent); }
.file[data-state="error"] { border-color: var(--error); }
.file[data-state="error"] .meta { color: var(--error); }
.file[data-state="done"] .meta { color: var(--done); }
.cancel {
  min-height: 2.75rem;
  padding: 0.5rem 0.875rem;
  border: 1px solid var(--border);
  border-radius: 0.5rem;
  background: var(--surface);
  color: var(--text);
  font: inherit;
  cursor: pointer;
}
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
CSS

Two attributes on the input are worth knowing. multiple lets people pick several files at once. accept tells the file chooser which types to offer, and on Android it lets the chooser offer the camera for images. It is only a hint, though: a dropped file, or someone switching the chooser to "All files", skips it. That is why the script checks the type again later, and the server checks it a third time.

Check it worked

Open index.html in your browser (open index.html on macOS, xdg-open index.html on Linux, or drag the file into a window). You see the heading, a white box with a dashed edge, the bold label Choose files, the hint, and a dark teal Choose Files or Browse button (the word depends on your browser) followed by No file chosen. Click in the empty space above the heading and press Tab: a teal ring appears around the file input. Press Enter or Space and your system's file chooser opens. Close it without choosing anything.

Step 2 · Write a small server that checks every upload

The page needs somewhere to send files. Write a Node.js server with no dependencies. It serves the three page files, and accepts POST /upload with the raw file as the request body and its type in the Content-Type header. Sending the bare file, rather than a multipart form, is how many storage services take uploads too, and it keeps the server short.

Bash
cd ~/upload-demo
cat > server.mjs <<'JS'
import { createServer } from 'node:http';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';

const PORT = 8787;
const MAX_BYTES = 5 * 1024 * 1024;

// Allowed types, and the bytes each real file of that type starts with.
const RULES = new Map([
  ['image/png', { ext: '.png', label: 'a PNG image', magic: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a] }],
  ['image/jpeg', { ext: '.jpg', label: 'a JPEG image', magic: [0xff, 0xd8, 0xff] }],
  ['application/pdf', { ext: '.pdf', label: 'a PDF', magic: [0x25, 0x50, 0x44, 0x46, 0x2d] }],
]);

// Only these paths are served. server.mjs and uploads/ never are.
const PAGES = new Map([
  ['/', ['index.html', 'text/html; charset=utf-8']],
  ['/style.css', ['style.css', 'text/css; charset=utf-8']],
  ['/upload.js', ['upload.js', 'text/javascript; charset=utf-8']],
]);

const uploadDir = new URL('./uploads/', import.meta.url);
await mkdir(uploadDir, { recursive: true });

class Rejected extends Error {
  constructor(status, message) {
    super(message);
    this.status = status;
  }
}

function sendJson(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
}

async function handleUpload(req, res) {
  try {
    const type = (req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
    const rule = RULES.get(type);
    if (!rule) throw new Rejected(415, 'Only PNG, JPEG and PDF files are accepted.');

    const length = Number(req.headers['content-length']);
    if (!Number.isInteger(length)) throw new Rejected(411, 'Send a Content-Length header.');
    if (length > MAX_BYTES) throw new Rejected(413, 'Files must be 5 MB or smaller.');

    // Count the bytes as they arrive, in case the header lied.
    const chunks = [];
    let size = 0;
    for await (const chunk of req) {
      size += chunk.length;
      if (size > MAX_BYTES) throw new Rejected(413, 'Files must be 5 MB or smaller.');
      chunks.push(chunk);
    }
    if (size !== length) throw new Rejected(400, 'The upload did not finish.');

    const body = Buffer.concat(chunks);
    if (!rule.magic.every((byte, i) => body[i] === byte)) {
      throw new Rejected(415, `The file content is not ${rule.label}.`);
    }

    // Never reuse the name the browser sent. Make a new one.
    const name = randomUUID() + rule.ext;
    await writeFile(new URL(name, uploadDir), body, { flag: 'wx' });
    sendJson(res, 201, { name, size });
  } catch (error) {
    // The browser cancelled, or the connection was closed. Nothing was saved.
    if (req.socket.destroyed) return;
    if (error instanceof Rejected) return sendJson(res, error.status, { error: error.message });
    console.error(error);
    sendJson(res, 500, { error: 'The server could not save the file.' });
  }
}

const server = createServer(async (req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');
  if (req.method === 'POST' && pathname === '/upload') return handleUpload(req, res);

  const page = PAGES.get(pathname);
  if (req.method === 'GET' && page) {
    try {
      const body = await readFile(new URL(page[0], import.meta.url));
      res.writeHead(200, { 'Content-Type': page[1], 'Cache-Control': 'no-store' });
      return res.end(body);
    } catch {
      // Fall through to 404 if the file is missing.
    }
  }
  sendJson(res, 404, { error: 'Not found' });
});

server.listen(PORT, '127.0.0.1', () => {
  console.log(`Uploader running at http://127.0.0.1:${PORT}/`);
});
JS

What the server checks, and why each check is there:

  • The declared type is on an allow list. Anything else gets 415 Unsupported Media Type before the body is read.
  • The size, twice. The Content-Length header is checked first, so an honest large upload is turned away at once with 413. Then the bytes are counted as they arrive, because a client can send any header it likes. Even a file that passes is held in memory only up to 5 MB.
  • The first bytes match the type. A PNG always starts with the same eight bytes, a JPEG with FF D8 FF and a PDF with %PDF-. A text file renamed to photo.png fails here, which no browser-side check can catch.
  • A new file name. The name the browser sent can contain ../, odd characters or another user's file name. The server ignores it and stores a random UUID with the right extension. { flag: 'wx' } refuses to overwrite an existing file.

Start the server and leave this terminal open:

Bash
node server.mjs

It prints Uploader running at http://127.0.0.1:8787/. The server listens on 127.0.0.1 only, so nothing else on your network can send it files.

Check it worked

Open a second terminal and fetch the page:

Bash
curl -s http://127.0.0.1:8787/ | grep '<h1>'

The output is <h1>Upload documents</h1>. Now open http://127.0.0.1:8787/ in your browser: you see the same page as before, styled, but served by your own server.

Step 3 · Check each file and preview images

Every file goes through the same check before anything is sent. The script is a classic script loaded with defer, so its top-level functions are also reachable from the DevTools console, which makes each piece easy to try on its own.

Start upload.js with the limits, the check and a function that builds one row of the file list:

Bash
cd ~/upload-demo
cat > upload.js <<'JS'
const MAX_BYTES = 5 * 1024 * 1024;
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'application/pdf'];
const list = document.querySelector('#file-list');
const announcer = document.querySelector('#status');
let nextId = 0;

// Returns why a file cannot be sent, or '' when it is fine.
function checkFile(file) {
  if (!ALLOWED_TYPES.includes(file.type)) return 'Not a PNG, JPEG or PDF file.';
  if (file.size > MAX_BYTES) return `Too large (${formatSize(file.size)}). The limit is 5 MB.`;
  if (file.size === 0) return 'The file is empty.';
  return '';
}

function formatSize(bytes) {
  if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
  return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

function announce(message) {
  announcer.textContent = message;
}

// One list row: preview, name, size or problem, progress bar, Cancel.
function makeRow(file, problem) {
  const id = `file-${nextId++}`;
  const row = document.createElement('li');
  row.className = 'file';
  row.innerHTML = `
    <div class="thumb" aria-hidden="true"></div>
    <div class="details">
      <p class="name" id="${id}-name" tabindex="-1"></p>
      <p class="meta"></p>
      <progress aria-labelledby="${id}-name" max="1" value="0" hidden></progress>
    </div>
    <button type="button" class="cancel" hidden>Cancel<span class="visually-hidden"></span></button>`;

  // File names come from the user, so they only ever go in as text.
  row.querySelector('.name').textContent = file.name;
  row.querySelector('.cancel span').textContent = ` upload of ${file.name}`;
  row.querySelector('.meta').textContent = problem || formatSize(file.size);
  if (problem) row.dataset.state = 'error';

  const thumb = row.querySelector('.thumb');
  if (!problem && file.type.startsWith('image/')) {
    const img = document.createElement('img');
    const url = URL.createObjectURL(file);
    img.alt = '';
    img.decoding = 'async';
    // The image keeps showing after the URL is revoked; the memory is freed.
    img.addEventListener('load', () => URL.revokeObjectURL(url), { once: true });
    img.addEventListener('error', () => URL.revokeObjectURL(url), { once: true });
    img.src = url;
    thumb.append(img);
  } else {
    thumb.textContent = (file.name.split('.').pop() || 'file').slice(0, 4).toUpperCase();
  }
  return row;
}
JS

Notes on the choices here:

  • The template holds no user data. The row's structure is written with innerHTML, but the file name, which a user controls, is set with textContent. A file called <img src=x onerror=alert(1)>.png is shown as text, not run.
  • URL.createObjectURL(file) gives a blob: address that points at the file in memory, so the preview appears without reading the file into a string. The browser keeps that file alive until the URL is revoked or the page closes. Revoking it as soon as the image has loaded frees the memory while the decoded picture stays on screen. On a phone with little memory, ten unrevoked camera photos add up.
  • The preview's alt is empty because the file name is right beside it; a screen reader would otherwise read the name twice.
  • The Cancel button has a hidden suffix, so with several files its accessible name is "Cancel upload of receipt.png", not five identical "Cancel" buttons.

Check it worked

Reload http://127.0.0.1:8787/, open DevTools (F12, or Cmd+Option+I on macOS) and go to the Console. Run:

JavaScript
const fake = new File(['hello'], 'notes.txt', { type: 'text/plain' });
checkFile(fake);
list.append(makeRow(fake, checkFile(fake)));

The console prints 'Not a PNG, JPEG or PDF file.', and a row appears under the drop zone with a grey TXT box, the name notes.txt and the reason in red, inside a red-edged box. Reload to clear it.

Step 4 · Upload with XMLHttpRequest and show progress

fetch() can report download progress by reading the response stream, but it has no event for bytes going up. Streaming request bodies can stand in for it in some browsers, but they need HTTP/2 or later and are not supported everywhere. XMLHttpRequest has had xhr.upload progress events for years, in every browser, which is why it is still the right tool for this one job.

Add the upload function:

Bash
cd ~/upload-demo
cat >> upload.js <<'JS'

function upload(file, row) {
  const xhr = new XMLHttpRequest();
  const bar = row.querySelector('progress');
  const meta = row.querySelector('.meta');
  const cancel = row.querySelector('.cancel');

  // No value attribute means "busy, amount unknown" until the first event.
  bar.removeAttribute('value');
  bar.hidden = false;
  cancel.hidden = false;
  meta.textContent = `Starting upload, ${formatSize(file.size)}`;

  xhr.upload.addEventListener('progress', (event) => {
    if (!event.lengthComputable) return;
    bar.max = event.total;
    bar.value = event.loaded;
    meta.textContent = `${Math.floor((event.loaded / event.total) * 100)}% of ${formatSize(event.total)}`;
  });

  xhr.addEventListener('load', () => {
    let reply = {};
    try { reply = JSON.parse(xhr.responseText); } catch { /* not JSON */ }
    if (xhr.status === 201) {
      bar.value = bar.max;
      finish(row, 'done', 'Uploaded');
    } else {
      finish(row, 'error', reply.error ?? `Upload failed (HTTP ${xhr.status}).`);
    }
  });
  xhr.addEventListener('error', () => finish(row, 'error', 'Network error. Check your connection and try again.'));
  xhr.addEventListener('abort', () => finish(row, 'cancelled', 'Cancelled'));

  cancel.addEventListener('click', () => {
    xhr.abort();
    // The button is now hidden, so move focus to something that stays.
    row.querySelector('.name').focus();
  });

  xhr.open('POST', '/upload');
  xhr.setRequestHeader('Content-Type', file.type);
  xhr.send(file);
}

function finish(row, state, message) {
  row.dataset.state = state;
  row.querySelector('.meta').textContent = message;
  row.querySelector('.cancel').hidden = true;
  row.querySelector('progress').hidden = state !== 'done';
  announce(`${row.querySelector('.name').textContent}: ${message}`);
}
JS

How it fits together:

  • xhr.send(file) sends the file itself. The browser streams it from disk; the script never reads it into memory.
  • Progress events fire on xhr.upload, not on xhr. The ones on xhr describe the response coming back. event.loaded and event.total are bytes, so they go straight into the bar's value and max.
  • A <progress> element is the right control. It has the progressbar role, its value is read by screen readers, and aria-labelledby names it after the file. The percentage is also written as text in the row, so the status does not depend on seeing the bar.
  • Every way the request can end has a handler. load covers any reply from the server, including 413 and 415, which still count as a "load" to XMLHttpRequest, so the status code is checked. error covers a dropped connection and abort covers Cancel.
  • finish announces the result through the status region, so a screen reader user hears "receipt.png: Uploaded" without moving focus.

Check it worked

With the server running and the page reloaded, run this in the Console:

JavaScript
const pdf = new File(['%PDF-1.7\n'], 'console-test.pdf', { type: 'application/pdf' });
const row = makeRow(pdf, '');
list.append(row);
upload(pdf, row);

A row for console-test.pdf appears with a PDF box, the bar fills almost at once and the text turns green: Uploaded. In your second terminal, ls ~/upload-demo/uploads lists one file with a long random name ending in .pdf, not console-test.pdf.

Step 5 · Accept picked and dropped files

Now connect the input and the drop zone. Both lead to the same addFiles function, so a picked file and a dropped file get exactly the same checks.

Bash
cd ~/upload-demo
cat >> upload.js <<'JS'

const input = document.querySelector('#files');
const zone = document.querySelector('.drop-zone');

function addFiles(files) {
  for (const file of files) {
    const problem = checkFile(file);
    const row = makeRow(file, problem);
    list.append(row);
    if (problem) announce(`${file.name}: ${problem}`);
    else upload(file, row);
  }
}

input.addEventListener('change', () => {
  addFiles([...input.files]);
  // Clear the input so choosing the same file again still fires "change".
  input.value = '';
});

// A drop is only allowed where dragover is cancelled.
zone.addEventListener('dragover', (event) => {
  event.preventDefault();
  event.dataTransfer.dropEffect = 'copy';
  zone.classList.add('is-over');
});
zone.addEventListener('dragleave', (event) => {
  if (!zone.contains(event.relatedTarget)) zone.classList.remove('is-over');
});
zone.addEventListener('drop', (event) => {
  event.preventDefault();
  zone.classList.remove('is-over');
  addFiles([...event.dataTransfer.files]);
});

// Outside the zone, a dropped file would replace the page. Refuse it there.
window.addEventListener('dragover', (event) => {
  event.preventDefault();
  if (!zone.contains(event.target)) event.dataTransfer.dropEffect = 'none';
});
window.addEventListener('drop', (event) => event.preventDefault());
JS

Three details make drag and drop behave:

  • dragover must call preventDefault(). By default the browser refuses drops on page elements; cancelling dragover is how an element says "I accept this". The drop handler cancels too, so the browser does not also open the file.
  • dragleave fires when the pointer moves onto a child, such as the label inside the zone. Checking relatedTarget keeps the highlight steady while the file is anywhere inside the box.
  • The window-level handlers stop a file that misses the zone from loading in the tab and throwing away whatever the person had on the page.

The files are copied into an array with [...files] before the input is cleared, because input.files is emptied when input.value is reset.

Check it worked

Reload the page. Drag a photo (PNG or JPEG under 5 MB) from your desktop or file manager over the box: the edge turns solid teal and the box fills with a pale teal tint. Drop it. A row appears with a thumbnail of your photo, the bar fills, and the text reads Uploaded. Drag a file over the heading instead: the pointer shows a "no drop" sign, and dropping does nothing. Then press Tab to the input, press Enter, pick a .txt file or anything over 5 MB, and confirm: its row shows the reason in red and no bar appears. On a phone, tapping Choose Files opens the system chooser, and drag and drop is not needed at all.

Step 6 · Watch progress and cancel on a slow connection

On your own machine an upload finishes before you can see the bar move. Slow the browser down to see what someone on a weak mobile signal sees.

In Chrome or Edge, open DevTools, go to the Network panel and change the throttling menu (it reads No throttling) to 3G, or the slowest preset your version offers. Throttling applies to uploads as well as downloads. Leave DevTools open, because throttling only applies while it is open.

Choose a photo of 2 to 5 MB and drop it on the box. The bar first shows the indeterminate "busy" style, then fills step by step while the text counts up, something like 12% of 3.4 MB. Before it finishes, click Cancel. The request stops, the bar disappears, the row reads Cancelled, and keyboard focus lands on the file name.

Cancelling matters most for the people with the least data. On a slow connection a wrong file can take minutes and cost real money, so the Cancel button is not an extra; it is how the person gets their data allowance back.

Check it worked

In the terminal, ls ~/upload-demo/uploads shows no new file for the cancelled photo: the server drops a request that is cut off part-way and never writes it. In the Network panel, the upload request for that photo shows as cancelled (Chrome writes (canceled) in the Status column). Set throttling back to No throttling when you are done.

Step 7 · Prove the server rejects what the browser lets through

Everything the page checks can be skipped by anyone who sends a request without the page. curl does that in one line. In your second terminal, try three bad uploads and one good one. First, a text file pretending to be a PNG:

Bash
cd ~/upload-demo
printf 'just some text' > fake.png
curl -s -w ' HTTP %{http_code}\n' -H 'Content-Type: image/png' --data-binary @fake.png http://127.0.0.1:8787/upload

The output is {"error":"The file content is not a PNG image."} HTTP 415. The header said PNG, the first bytes did not.

Next, a 6 MB file and a type that is not on the list:

Bash
cd ~/upload-demo
head -c 6000000 /dev/zero > big.pdf
curl -s -w ' HTTP %{http_code}\n' -H 'Content-Type: application/pdf' --data-binary @big.pdf http://127.0.0.1:8787/upload
curl -s -w ' HTTP %{http_code}\n' -H 'Content-Type: text/html' --data-binary @fake.png http://127.0.0.1:8787/upload

The first prints {"error":"Files must be 5 MB or smaller."} HTTP 413, the second {"error":"Only PNG, JPEG and PDF files are accepted."} HTTP 415.

Finally, a small file that really starts like a PDF:

Bash
cd ~/upload-demo
printf '%%PDF-1.7\n' > tiny.pdf
curl -s -w ' HTTP %{http_code}\n' -H 'Content-Type: application/pdf' --data-binary @tiny.pdf http://127.0.0.1:8787/upload

It prints something like {"name":"3f1c9e0a-....pdf","size":9} HTTP 201, with a different random name each time.

The browser checks exist to save the person time and data. The server checks exist to protect the server. You need both, and they must agree: keep the limit and the list of types in one place in a real project, such as a shared config the server also sends to the page. A production server goes further than this one, for example by streaming large files to storage instead of memory, scanning them for malware, and serving uploads from a separate domain so a crafted file can never run as part of your site.

Check it worked

You saw HTTP 415, HTTP 413, HTTP 415 and HTTP 201, in that order. ls ~/upload-demo/uploads lists only files with random names: the PDF from the Console step, the photos you uploaded and the new copy of tiny.pdf. None of the rejected files is there.

Step 8 · Test the uploader with Playwright

A test keeps all of this working when someone changes the script later. Install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux, which can ask for your password. Run these in the second terminal, with the server still running in the first:

Bash
cd ~/upload-demo
npm init -y > /dev/null
npm install playwright@1.65.1
npx playwright install --with-deps chromium

Playwright's setInputFiles fills a file input with files made in memory, the way a person's pick would, so the test needs no sample files on disk. For drag and drop it builds a DataTransfer in the page and fires a drop event on the zone. To test Cancel, page.route holds the upload request for three seconds so there is time to click the button.

Bash
cd ~/upload-demo
cat > test-upload.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
import { readdir } from 'node:fs/promises';

const BASE = 'http://127.0.0.1:8787/';
// A real 1 by 1 pixel PNG.
const png = Buffer.from(
  'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
  'base64',
);
const savedCount = async () => (await readdir('uploads')).length;
const before = await savedCount();

const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
const errors = [];
page.on('pageerror', (error) => errors.push(error.message));
await page.goto(BASE);
const row = (name) => page.locator('#file-list li', { hasText: name });

// The file input is a labelled control, first in the tab order.
const input = page.getByLabel('Choose files');
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement.id), 'files');

// One good file, one wrong type, one too large, picked together.
await input.setInputFiles([
  { name: 'receipt.png', mimeType: 'image/png', buffer: png },
  { name: 'notes.txt', mimeType: 'text/plain', buffer: Buffer.from('hello') },
  { name: 'scan.pdf', mimeType: 'application/pdf', buffer: Buffer.alloc(6 * 1024 * 1024) },
]);

await row('receipt.png').getByText('Uploaded').waitFor();
const bar = await row('receipt.png')
  .getByRole('progressbar', { name: 'receipt.png' })
  .evaluate((p) => ({ value: p.value, max: p.max }));
assert.equal(bar.value, bar.max, 'the progress bar is full');

// The preview shows the image, and its blob: URL is revoked afterwards.
const preview = row('receipt.png').locator('img');
assert.equal(await preview.evaluate((img) => img.decode().then(() => img.naturalWidth)), 1);
const src = await preview.getAttribute('src');
assert.ok(src.startsWith('blob:'));
await page.waitForFunction((url) => fetch(url).then(() => false, () => true), src);

// Rejected in the browser, with the reason shown and nothing sent.
assert.match(await row('notes.txt').textContent(), /Not a PNG, JPEG or PDF file\./);
assert.match(await row('scan.pdf').textContent(), /Too large \(6\.0 MB\)\. The limit is 5 MB\./);
assert.equal(await row('notes.txt').locator('progress').isVisible(), false);
assert.equal(await row('scan.pdf').locator('progress').isVisible(), false);

// Drag and drop: a drop event carrying a PDF.
await page.locator('.drop-zone').evaluate((zone) => {
  const data = new DataTransfer();
  data.items.add(new File(['%PDF-1.7\n%demo\n'], 'letter.pdf', { type: 'application/pdf' }));
  zone.dispatchEvent(new DragEvent('drop', { dataTransfer: data, bubbles: true, cancelable: true }));
});
await row('letter.pdf').getByText('Uploaded').waitFor();
assert.equal(await savedCount(), before + 2, 'the server saved exactly the two good files');

// Cancel: hold the request so there is time to press the button.
await page.route('**/upload', async (route) => {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  await route.continue().catch(() => {});
});
await input.setInputFiles({ name: 'slow.png', mimeType: 'image/png', buffer: png });
await row('slow.png').getByRole('button', { name: 'Cancel upload of slow.png' }).click();
await row('slow.png').getByText('Cancelled').waitFor();
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'slow.png', 'focus moves to the file name');
assert.equal(await page.locator('#status').textContent(), 'slow.png: Cancelled');
await page.unrouteAll({ behavior: 'ignoreErrors' });

// No sideways scrolling on a phone-sized screen, and no script errors.
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(overflow, false);
assert.deepEqual(errors, []);

await browser.close();
console.log('PASS: files checked, uploaded, previewed and cancelled');
JS
node test-upload.mjs

The test finds things the way assistive technology does, by role and name: the input by its label, the bar as a progressbar named after the file, the Cancel button by its full name. If someone breaks the label or drops the hidden suffix, the test fails as well. It runs at 390 by 844 pixels, a common phone size, because most people who need an upload field like this will be on a phone.

Check it worked

The last line of output is PASS: files checked, uploaded, previewed and cancelled. To see it fail for the right reason, change const MAX_BYTES = 5 * 1024 * 1024; at the top of upload.js to 10 * 1024 * 1024 and run node test-upload.mjs again: the 6 MB scan.pdf now passes the browser check and is sent, so the server has to turn it away instead, and the test stops with an AssertionError because its row no longer says Too large. Change it back and the test passes again.

Step 9 · Clean up

Stop the server in its terminal with Ctrl+C.

Then remove the demo folder, which also removes the uploaded files and the local Playwright install. The browser Playwright downloaded stays in its shared cache; npx playwright uninstall removes that too if you no longer need it.

Bash
cd ~
rm -rf ~/upload-demo

Check it worked

ls ~/upload-demo reports that there is no such file or directory, and http://127.0.0.1:8787/ no longer loads.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Digital Transformation

Get new tutorials

New tutorials, about twice a month.