BT San Technology

2 September 2026

Document Uploads in a Web App: File Type, Access Rights and Retention

27 min read · Websites and web apps

Illustration: a document scanner beside a file-upload screen showing document access rights
AI-generated illustration

An upload form is often built in half a day: accept a file, name it, store it in a folder, and paste the link into a page. The problems come later. A file named .jpg that is really an HTML page with a script in it. A filename that walks out of the folder. A link where guessing the next number opens another customer's document. Or an ID card copy that has sat on the server for three years because nobody dares to delete it.

This article walks through writing an upload and download service for business documents (PDF, JPG, PNG) that closes these gaps one by one. It uses TypeScript that Node 24 runs directly, with nothing to install. A manager can read the explanations and tables and see what to ask the team. An engineer can run the code and follow along.

The real problem: an incoming file is someone else's data and someone else's code at the same time

A file sent by a user has two sides to watch at once. One side is data that must be stored for the right person (a tax invoice, an ID card copy, a purchase order). The other side is something that the system and the browser will read or run. If you check only the filename, both sides stay open.

Consider three hypothetical situations, not any BT San customer's project.

  • Accounting firm client portal: a client uploads a tax invoice as a PDF. The system stores the file in a public folder under its original name. Someone guesses the URL, changes the company name in the link, and opens another client's document.
  • Job application or membership system: a user attaches photo.jpg, which is really an HTML file. If the server returns it with the Content-Type the user claimed, or the browser guesses the type itself and shows it as a web page, the script runs on the company's domain.
  • Internal purchasing system: an employee attaches a 2 GB purchase order (on purpose or by mistake). The server reads the whole thing into memory before checking the size, and the machine runs out of RAM before it can reject the file.

Each case is fixed in a different place: per-document permissions, checking the real content together with headers on the response, and limiting the size while reading. The point people often forget is how long the file will live and who deletes it.

What the references say: what is known, and what we must not assume

TopicWhat the document saysEffect on our code
File typeThe OWASP File Upload Cheat Sheet says to use an allow-list of the extensions you need, not to trust Content-Type because it can be forged, and to check the file signature, but warns not to rely on it alone because it is easy to bypassChecking magic bytes is one gate, not the only gate. We also need headers on the response and an additional scan.
Name and storageOWASP says to rename the file with a system-generated name and to store it outside the webroot or on another server. The Unrestricted File Upload page says to remove execute permission from the upload folder.The storage name is random. The original name is sanitized metadata.
SizeOWASP says to set a file size limit and to allow uploads only for authorized usersCut off while reading, not after reading everything
On responseThe Unrestricted File Upload page says to send Content-Disposition: attachment and X-Content-Type-Options: nosniff. MDN states that nosniff turns off the browser's type guessing, and that filename* uses the encoding from RFC 5987, so an ASCII filename should be included as a fallback alongside it.Always set the headers ourselves, from the type we verified
Names with a pathRFC 6266 states that the filename is only a suggestion and that folder parts in filename should not be trusted. Keep only the part after the last / or \.Strip the path at intake
Type guessingThe WHATWG MIME Sniffing standard warns that if a server serves user-uploaded files with a low-privilege type, a browser may treat them as HTML and run scripts. It defines byte signatures for PNG (89 50 4E 47 0D 0A 1A 0A), JPEG (FF D8 FF) and PDF (25 50 44 46 2D).Use these signatures in the code, and always send nosniff
Summary of the OWASP, MDN, RFC 6266 and WHATWG documents as read on 2026-11-21. Read the latest version of each document before applying any detail.

OWASP itself states that checking the file signature is easy to bypass when used alone. The example in this article therefore shows a file that passes this gate and is still controlled by the quarantine status and the headers on the response.

Overview of the example

All the code is in the folder examples/web-app-secure-file-upload/. It uses only Node 24 built-ins, with no npm install, and runs directly with node file.ts. The abnormal test files are created at run time. There are no dangerous files or malware samples in the folder.

FilePurpose
sniff.tsChecks the type from magic bytes against an allow-list
names.tsSanitizes the original filename and builds a Content-Disposition that supports Thai filenames
limit.tsReads a stream and stops when it passes the limit
store.tsRandom-name storage, the quarantine to available status, a scan hook, per-document permissions, audit and retention
server.tsUpload and download endpoints using node:http
demo.ts / upload.test.tsA script that uploads good and abnormal files, and a node:test suite

The order of an upload is: check identity, check Content-Length up front, read the body with a limit, check magic bytes, sanitize the name, store it as a randomly named file in quarantine status, and then scan. The steps follow.

Step 1: cut off the size while reading, not after reading everything

The node:http request is a readable stream (the Node docs state that IncomingMessage is a Readable), so it can be read chunk by chunk while counting the cumulative bytes. When the count passes the limit, the code stops and does not keep the remaining chunks.

limit.ts
// อ่าน stream ทีละ chunk และหยุดทันทีที่เกินเพดาน ไม่รอเก็บทั้งก้อนแล้วค่อยเช็กขนาด
export type ReadResult =
  | { ok: true; body: Buffer }
  | { ok: false; reason: "too_large"; bytesRead: number };

export async function readLimited(stream: AsyncIterable<Buffer | Uint8Array>, maxBytes: number): Promise<ReadResult> {
  const chunks: Buffer[] = [];
  let total = 0;
  for await (const chunk of stream) {
    total += chunk.length;
    if (total > maxBytes) return { ok: false, reason: "too_large", bytesRead: total };
    chunks.push(Buffer.from(chunk));
  }
  return { ok: true, body: Buffer.concat(chunks) };
}
limit.ts stops reading as soon as the limit is exceeded
  • Checking Content-Length up front is only a shortcut. A dishonest client can lie about this value or use chunked encoding and not send it at all. The actual byte counter is therefore the gate you can trust.
  • When the limit is exceeded, respond 413 with Connection: close, and close the connection after the response, so the client cannot keep sending the rest.
  • The limit should differ by document type, for example a few MB for an ID card scan and tens of MB for a contract PDF. It must also match the limit on the reverse proxy in front.
server.ts · lines 23–43
    if (req.method === "POST" && url.pathname === "/documents") {
      // simplified: รับ body ดิบ (ไม่ใช่ multipart) ชื่อไฟล์มาใน header x-filename แบบ percent-encoded
      const declared = Number(req.headers["content-length"] ?? 0);
      const done = () => res.once("finish", () => req.destroy()); // ตัดการเชื่อมต่อหลังตอบ 413 เสร็จ
      if (declared > maxBytes) {
        done();
        return send(res, 413, { error: "too_large", limit: maxBytes }, { connection: "close" });
      }
      const r = await readLimited(req, maxBytes);
      if (!r.ok) {
        done();
        return send(res, 413, { error: "too_large", limit: maxBytes, bytesRead: r.bytesRead }, { connection: "close" });
      }
      if (r.body.length === 0) return send(res, 400, { error: "empty_file" });
      const kind = detectKind(r.body); // ไม่ดู content-type ที่ client ส่งมาเลย
      if (!kind) return send(res, 415, { error: "unsupported_type" });
      let raw = "";
      try { raw = decodeURIComponent(String(req.headers["x-filename"] ?? "")); } catch { /* ใช้ชื่อว่างต่อ */ }
      const doc = await store.put(user, sanitizeName(raw), kind, r.body);
      return send(res, 201, { id: doc.id, state: doc.state, kind, name: doc.originalName, size: doc.size });
    }
server.ts, upload side: checks the limit and the type, and sanitizes the name before storing

Step 2: check the type from the content, not the extension or Content-Type

The extension and the Content-Type both come from the client, and either can be changed in one line. The code therefore reads the first bytes and compares them with the signatures of the PDF, JPEG and PNG types in the allow-list. If none of the three matches, it responds 415, whatever the client claims the file is.

sniff.ts · lines 18–25
// คืน null ถ้าไม่อยู่ใน allow-list (รวมไฟล์ว่าง HTML สคริปต์ ฯลฯ)
export function detectKind(buf: Uint8Array): FileKind | null {
  if (startsWith(buf, PNG)) return "png";
  if (startsWith(buf, JPEG)) return "jpeg";
  // simplified: PDF ตรวจแค่หัวไฟล์; ของจริงควรมีตัวแยกวิเคราะห์ PDF หรือ CDR ช่วยด้วย
  if (startsWith(buf, PDF)) return "pdf";
  return null;
}
sniff.ts returns null when the type is not in the allow-list

The verified type is then used in two places: as the Content-Type on the response, and as a field in the metadata. The value the client claimed is never stored. One limit to know: a file that starts with FF D8 FF and has HTML appended will pass this gate. This is not hidden. In the example, case 7 is a JPEG with a marker text appended. It passes the type check but is rejected by the simulated scanner, and on download nosniff and attachment add another layer.

Step 3: the original filename is only metadata

Thai users name files in Thai as a matter of course, so sanitizing must not mean stripping everything that is not ASCII. This function strips the path (both / and \), removes control characters and invisible characters such as the text direction switchers, replaces characters that are forbidden in file systems, strips leading dots, and limits the length, but it keeps Thai letters.

names.ts · lines 1–10
// ชื่อไฟล์เดิมเก็บเป็น metadata เท่านั้น: ล้างให้ปลอดภัยแต่คงภาษาไทยไว้ และสร้าง Content-Disposition
export function sanitizeName(raw: string): string {
  let name = raw.normalize("NFC");
  name = name.split(/[\\/]/).pop() ?? ""; // ตัด path ทิ้ง เหลือชื่อท้ายสุด
  name = name.replace(/[\p{Cc}\p{Cf}]/gu, ""); // อักขระควบคุมและตัวล่องหน (เช่น RTL override)
  name = name.replace(/[<>:"|?*]/g, "_");
  name = name.replace(/^[.\s]+/, "").replace(/[.\s]+$/, ""); // ไม่ขึ้นต้นด้วยจุด (".." ".htaccess")
  if (name.length > 100) name = name.slice(0, 100);
  return name === "" ? "document" : name;
}
names.ts: the sanitizeName function

The sanitized name is never used as the name on disk. The real file is written under a random name with no extension, in a private folder (see store.ts below). The original name is used only for display and for naming the download. On the response it must be encoded correctly per RFC 5987. That encoding does not include the characters ' ( ) * that encodeURIComponent lets through, so we convert them ourselves, and we add an ASCII filename as a fallback for older programs.

names.ts · lines 13–20
function encodeRfc5987(s: string): string {
  return encodeURIComponent(s).replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase());
}

export function contentDisposition(disposition: "attachment" | "inline", name: string): string {
  const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
  return `${disposition}; filename="${ascii}"; filename*=UTF-8''${encodeRfc5987(name)}`;
}
names.ts: builds Content-Disposition with both filename and filename*

Step 4: store the file under a random name outside the public area, and hold it in quarantine

put writes the file with the wx flag (never overwrite an existing file), a random name and no extension. It then records the metadata with quarantine status and adds the file to the scan queue.

store.ts · lines 23–33
  async function put(owner: string, originalName: string, kind: FileKind, data: Buffer): Promise<Doc> {
    await mkdir(opts.dir, { recursive: true });
    const id = randomUUID();
    const storedName = randomUUID().replaceAll("-", ""); // ไม่มีนามสกุล ไม่เกี่ยวกับชื่อเดิม
    await writeFile(join(opts.dir, storedName), data, { flag: "wx" });
    const doc: Doc = { id, owner, originalName, kind, size: data.length, state: "quarantine", createdAt: now(), storedName };
    docs.set(id, doc);
    queue.push(id);
    log(owner, "upload", id, `${kind} ${data.length} bytes`);
    return doc;
  }
store.ts: the put function

The scanner is an injected function. In the example it is a stub that looks for a marker text that we plant ourselves. The result is available or rejected, and a rejected file is deleted immediately. A real system uses antivirus or a scanning service, and for PDFs and images should consider CDR (Content Disarm and Reconstruct), as OWASP mentions. While a file has not passed, it cannot be downloaded.

store.ts · lines 35–44
  // worker ของจริงเรียกจากคิวงาน; ตัวอย่างนี้เรียกเองเพื่อให้ผลลัพธ์คงที่
  async function runScans(): Promise<void> {
    while (queue.length > 0) {
      const doc = docs.get(queue.shift()!)!;
      const verdict = await opts.scan(await readFile(join(opts.dir, doc.storedName)));
      doc.state = verdict === "clean" ? "available" : "rejected";
      log("scanner", "scan", doc.id, verdict);
      if (verdict === "infected") await rm(join(opts.dir, doc.storedName), { force: true });
    }
  }
store.ts: runScans changes the status according to the scan result

Step 5: check permissions on every download, and answer 404 the same way every time

Hiding a button on the screen is not access control. Every request must check that the document belongs to the requester. If it does not, respond as if the file does not exist (a 404 with the same message). If you respond 403 with details, an attacker learns that the id really exists, and counting 404s against 403s can be used to guess ids. Every denial is recorded as access_denied.

store.ts · lines 46–54
  // เจ้าของเท่านั้น; id ของคนอื่นกับ id ที่ไม่มี ให้ผลเหมือนกัน (undefined) เพื่อไม่เปิดเผยว่ามีไฟล์นั้น
  function find(id: string, user: string): Doc | undefined {
    const d = docs.get(id);
    if (!d || d.owner !== user || d.state === "expired") {
      log(user, "access_denied", id);
      return undefined;
    }
    return d;
  }
store.ts: the find function checks the owner

The example uses the simplest rule: only the owner. Real work usually has roles, for example the accounting department sees the whole company's documents and an auditor has read-only access. That is a question of resource-level permission design. See the related article.

server.ts · lines 45–61
    const m = /^\/documents\/([0-9a-f-]{36})$/.exec(url.pathname);
    if (req.method === "GET" && m) {
      const doc = store.find(m[1]!, user);
      if (!doc) return send(res, 404, { error: "not_found" }); // ข้อความเดียวกันทั้งกรณีไม่มีและไม่ใช่ของคุณ
      if (doc.state !== "available") return send(res, 409, { error: "not_ready", state: doc.state });
      const inline = url.searchParams.get("inline") === "1";
      const data = await store.read(doc, user);
      res.writeHead(200, {
        "content-type": mimeOf[doc.kind], // จากการตรวจจริง ไม่ใช่ที่ client อ้าง
        "content-length": String(data.length),
        "content-disposition": contentDisposition(inline ? "inline" : "attachment", doc.originalName),
        "x-content-type-options": "nosniff",
        "content-security-policy": "default-src 'none'; sandbox",
        "cache-control": "private, no-store",
      });
      return res.end(data);
    }
server.ts, download side: the headers that are set every time
  • Content-Type comes from the type we verified ourselves, not from what the client once claimed.
  • Content-Disposition is attachment by default. Use inline only when the user asks to view it on the page and the type is in the allow-list.
  • X-Content-Type-Options: nosniff turns off the browser's type guessing, as MDN and OWASP state.
  • Content-Security-Policy with default-src none and sandbox, for the inline viewing case. If you use it with PDFs, test it with the PDF viewer in the browsers your customers use, because the sandbox may affect rendering.
  • Cache-Control: private, no-store stops intermediaries and shared browsers from keeping the document.

Step 6: retention: delete on schedule, and keep a record

Data that is never deleted becomes a liability, especially ID card copies. The example has a sweep job that deletes the real files older than N days, keeps only metadata with no content, and writes an audit entry saying what the system deleted and when. The tests use a simulated clock so there is no need to wait 90 days.

store.ts · lines 61–73
  // retention: ลบไฟล์จริงที่เก่าเกิน N วัน เก็บเฉพาะ metadata และ audit
  async function sweep(retentionDays: number): Promise<number> {
    const cutoff = now() - retentionDays * 86_400_000;
    let n = 0;
    for (const d of docs.values()) {
      if (d.state === "expired" || d.createdAt > cutoff) continue;
      await rm(join(opts.dir, d.storedName), { force: true });
      d.state = "expired";
      log("system", "retention_delete", d.id, `older than ${retentionDays} days`);
      n++;
    }
    return n;
  }
store.ts: the sweep function

There is no universal retention period. It must be set according to the purpose of the document and the laws that apply. A tax invoice, for example, may have its own retention requirements, while an ID card copy should be kept only as long as necessary. Have your legal team or a PDPA consultant confirm this before you set the value.

A real run: good files and abnormal files

demo.ts starts a server at 127.0.0.1 on a random port, creates the test files itself at run time, and sends them in with node:http. Every request carries a Content-Type of image/jpeg to prove that this value is not trusted. It also sends them chunked with no Content-Length, so the stream has to be cut in the middle.

demo.ts · lines 23–34
function call(method: string, path: string, user: string, body?: Buffer, headers: Record<string, string> = {}): Promise<Res> {
  return new Promise((resolve, reject) => {
    const req = request({ host: "127.0.0.1", port, method, path, headers: { "x-user": user, ...headers } }, (res) => {
      const parts: Buffer[] = [];
      res.on("data", (c) => parts.push(c));
      res.on("end", () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: Buffer.concat(parts) }));
    });
    req.on("error", reject);
    if (body) req.write(body); // ไม่ส่ง content-length: ใช้ chunked เพื่อให้ต้องตัดกลาง stream
    req.end();
  });
}
demo.ts: the call function sends chunked requests
output.txt
เพดานขนาด 65536 bytes, content-type ที่ client ส่งทุกครั้งคือ image/jpeg (เพื่อพิสูจน์ว่าไม่ถูกเชื่อ)
1 PDF ชื่อไทย (somchai)            -> 201 {"id":"7742c202-2d3e-462c-8c01-ee45420e3806","state":"quarantine","kind":"pdf","name":"ใบกำกับภาษี มค69.pdf","size":689}
2 ID-card scan png                 -> 201 {"id":"43d44b0f-d446-4312-a833-17aae2025375","state":"quarantine","kind":"png","name":"สำเนาบัตร.png","size":208}
3 .jpg ที่จริงคือ HTML             -> 415 {"error":"unsupported_type"}
4 ไฟล์ใหญ่เกินเพดาน (300000 B)     -> 413 {"error":"too_large","limit":65536,"bytesRead":130898}
5 ไฟล์ว่าง 0 byte                  -> 400 {"error":"empty_file"}
6 ชื่อ ../../etc/passwd.pdf        -> 201 {"id":"035de279-fddd-4ff3-88ec-af4be63c4c6b","state":"quarantine","kind":"pdf","name":"passwd.pdf","size":689}
7 JPEG ที่มี marker สแกนเนอร์      -> 201 {"id":"a52a8de8-6cff-4a9a-9917-7f543071ca0b","state":"quarantine","kind":"jpeg","name":"marked.jpg","size":23}
8 ดาวน์โหลดระหว่าง quarantine      -> 409 {"error":"not_ready","state":"quarantine"}
9 ดาวน์โหลดหลังสแกนผ่าน            -> 200 689 bytes
   content-type: application/pdf
   content-disposition: attachment; filename="___________ __69.pdf"; filename*=UTF-8''%E0%B9%83%E0%B8%9A%E0%B8%81%E0%B8%B3%E0%B8%81%E0%B8%B1%E0%B8%9A%E0%B8%A0%E0%B8%B2%E0%B8%A9%E0%B8%B5%20%E0%B8%A1%E0%B8%8469.pdf
   x-content-type-options: nosniff
   content-security-policy: default-src 'none'; sandbox
10 อีกคน (malee) ขอ id ของ somchai -> 404 {"error":"not_found"}
11 id ที่ไม่มีอยู่จริง (malee)     -> 404 {"error":"not_found"}

ไฟล์ในที่เก็บส่วนตัว (ชื่อสุ่ม ไม่มีนามสกุล):
   0765b49f...
   0adaf856...
   67e52b80...

retention 90 วัน: ปิด 4 รายการ (นาฬิกาจำลองเดินไป 91 วัน; รายการที่ถูกปฏิเสธไม่มีไฟล์เหลือแล้ว)
12 ดาวน์โหลดหลังหมดอายุ            -> 404 {"error":"not_found"}

บันทึก audit:
  somchai  upload            1a923c pdf 689 bytes
  somchai  upload            e2bbcd png 208 bytes
  somchai  upload            57f2cd pdf 689 bytes
  somchai  upload            4b4b79 jpeg 23 bytes
  scanner  scan              1a923c clean
  scanner  scan              e2bbcd clean
  scanner  scan              57f2cd clean
  scanner  scan              4b4b79 infected
  somchai  download          1a923c 
  malee    access_denied     1a923c 
  malee    access_denied     37965e 
  system   retention_delete  1a923c older than 90 days
  system   retention_delete  e2bbcd older than 90 days
  system   retention_delete  57f2cd older than 90 days
  system   retention_delete  4b4b79 older than 90 days
  somchai  access_denied     1a923c 
Output from a real run on 2026-11-21 with node demo.ts (Node 24). The ids are random, and the bytesRead values depend on chunk size, so they can differ from run to run.

Reading the results one by one

  1. Cases 1 and 2: a PDF with a Thai filename and a PNG image pass the type check and get 201, in quarantine status. The Thai name is stored intact.
  2. Case 3: the file photo.jpg, which is really HTML, gets 415 even though the client claimed image/jpeg.
  3. Case 4: a 300000-byte file is over the 65536 limit and gets 413. bytesRead shows that only 130898 bytes were read (the size depends on how many chunks arrived before the cut), so it was not read in full.
  4. Case 5: an empty file gets 400 empty_file.
  5. Case 6: the name ../../etc/passwd.pdf is sanitized to passwd.pdf. The file is stored under a random name, and nothing ends up outside the storage folder.
  6. Case 7: a JPEG with a marker appended passes the type check and enters quarantine, but the simulated scanner rejects it (see the audit at the end of the output).
  7. Cases 8 and 9: a download during quarantine gets 409 not_ready. After the scan passes it gets 200 with all headers. The Thai name is in filename*, and the fallback filename is underscores.
  8. Cases 10 and 11: Malee asks for Somchai's id and for an id that does not exist. Both get exactly the same 404 message.
  9. Case 12: after the clock moves forward 91 days, the sweep closes 4 records. A download gets 404, and the audit has a retention_delete line for every record.

The test suite

upload.test.ts has 4 cases. Running node --test upload.test.ts gives 4 passes. They cover magic bytes (including HTML and an empty file), name sanitizing (Unix and Windows paths, control characters, Thai names, and the filename* encoding), stream cut-off that counts the chunks actually produced and checks that fewer than ten out of a thousand were read, and cross-user download through a real server that must get the same 404 as a nonexistent id, together with the quarantine case and the oversize file.

upload.test.ts · lines 32–38
test("เกินเพดาน: หยุดอ่านกลาง stream ไม่กิน chunk ที่เหลือ", async () => {
  let produced = 0;
  async function* gen() { for (let i = 0; i < 1000; i++) { produced++; yield Buffer.alloc(100); } }
  const r = await readLimited(Readable.from(gen()), 450);
  assert.equal(r.ok, false);
  assert.ok(produced <= 10, `อ่านไป ${produced} chunk`);
});
upload.test.ts: tests that reading stops partway

A real system: what to change next

  • File storage: use object storage with a private bucket. Serve downloads through the app or a short-lived signed URL, keep its account and permissions separate from the web server, and set a bucket lifecycle rule alongside the sweep job.
  • Scanning: connect to antivirus or a scanning service, run it in a job queue separate from the web app, and consider CDR for PDFs and images that will be passed on to others. The example is only a stub.
  • Receiving the body: use a multipart parser that has been proven in production, and set limits on the number of files, the filename length and the request timeout. The example takes a raw body to keep the code short.
  • Personal data: an ID card copy is data that must be kept only as needed, for a clear purpose, with limited access and a deletion date. Have the person responsible for PDPA confirm the legal basis and the period, and consider encrypting files at rest.
  • Backups: a file deleted by retention may still exist in a backup set. Set the backup retention to match, and rehearse a restore, checking that the metadata and the files agree.
  • Audit: keep it in a table that cannot be edited in general (append-only), with the actor, the time and the document id. Do not put file content or full names into the log.
  • Rate limiting: limit the number of uploads per user per hour and the total space per account, so storage cannot be filled up.

Hypothetical examples: adapting it to three businesses

An accounting firm's client portal

Permissions have two levels. A client sees their own company's documents. An accountant sees only the clients assigned to them. Adjust the find function to check this relationship. Set retention by document type, and the audit can answer who opened whose tax invoice and when.

A job application system that takes ID card copies and diplomas

These documents hold highly sensitive personal data. Set a short retention for applicants who are not selected, turn off inline viewing so downloads go only through HR, and produce a weekly report of the documents that were deleted.

A factory's internal purchasing system

Purchase orders and quotations are large PDFs. Adjust the limit by document type, link each document to its purchase order number, and have the quarantine status send a notification when a file is rejected, so IT can check it.

Common mistakes, and a checklist

  • Trusting the extension or Content-Type the client sends.
  • Using the original filename as the name on disk, or storing in a folder that the web server serves directly.
  • Checking the size after reading the whole file into memory.
  • Checking permissions on the screen but not at the download endpoint, or using sequential ids that can be guessed.
  • Responding 403 with details when the file is not the requester's, which reveals that the id exists.
  • Forgetting nosniff and attachment on the response, or letting the browser open user files on the main domain.
  • No deletion date, no audit, and nobody responsible for retention.
  • Testing with real dangerous files on production instead of self-made test files in a separate environment.
  1. Define the file types you need and the size limit for each document type.
  2. Cut off the size while reading the stream, and set the limit on the reverse proxy to match.
  3. Check the type from the content, and do not store the value the client claimed.
  4. Sanitize the original filename and keep it as metadata, and name the file on disk randomly, outside the public area.
  5. Hold files in quarantine until the scan passes.
  6. Check per-document permissions every time, and respond as if the file does not exist when it is not the requester's.
  7. Send Content-Disposition, nosniff, CSP and Cache-Control based on the type you verified yourself.
  8. Set retention with a named owner, and record an audit of uploads, downloads, denials and deletions.
  9. Before release, test with wrong-type files, oversize files, odd names, empty files and users without permission.

Cautions about the example: it uses a user from a hypothetical header instead of a real session, takes a raw body instead of multipart, uses a stub scanner, keeps metadata in memory (lost on restart), has no rate limit, does no file encryption, and checks a PDF only by its file header. Use it as a learning example, not as ready-to-use code. All data is self-made.

References

  1. OWASP — File Upload Cheat Sheet (allow-list, Content-Type, signature, random names, size, CDR) (accessed 2026-11-21)
  2. OWASP — Unrestricted File Upload (ย้ายมาจาก owasp.org/www-community) (accessed 2026-11-21)
  3. MDN — Content-Disposition (attachment, filename*) (accessed 2026-11-21)
  4. MDN — X-Content-Type-Options (nosniff) (accessed 2026-11-21)
  5. RFC 6266 — Use of the Content-Disposition Header Field in HTTP (accessed 2026-11-21)
  6. WHATWG — MIME Sniffing Standard (byte patterns, upload risk) (accessed 2026-11-21)
  7. Node.js — Stream (HTTP request เป็น Readable, readable.destroy) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer