File Uploads
Profile pictures, CSV imports, PDF invoices — sooner or later an API has to accept files. Files don't fit nicely into JSON, so browsers send them as multipart/form-data: a body split into parts, each with its own headers, separated by a boundary string.
What a multipart body looks like
POST /avatars HTTP/1.1
Content-Type: multipart/form-data; boundary=----x7Fq
------x7Fq
Content-Disposition: form-data; name="caption"
My new avatar
------x7Fq
Content-Disposition: form-data; name="avatar"; filename="me.png"
Content-Type: image/png
<binary PNG bytes…>
------x7Fq--Text fields and files travel side by side. Express's built-in parsers do not understand this format — express.json() and express.urlencoded() skip it — so you need a multipart parser.
| Package | Style |
|---|---|
multer |
the classic Express middleware; stores files on disk or in memory |
busboy |
low-level streaming parser (multer is built on it) |
formidable |
standalone parser, works with any framework |
Uploading with multer
const express = require('express');
const multer = require('multer');
const path = require('node:path');
const upload = multer({
dest: path.join(__dirname, 'uploads'), // temp file per upload, random name
limits: { fileSize: 2 * 1024 * 1024, files: 1 }, // 2 MB, one file
fileFilter: (req, file, cb) => {
const ok = ['image/png', 'image/jpeg', 'image/webp'].includes(file.mimetype);
cb(ok ? null : Object.assign(new Error('Only PNG, JPEG or WebP images'), { status: 415 }), ok);
},
});
const app = express();
app.post('/avatars', upload.single('avatar'), (req, res) => {
// req.file: { fieldname, originalname, mimetype, size, path, … }
// req.body: the text fields, e.g. { caption: 'My new avatar' }
res.status(201).json({ stored: req.file.filename, size: req.file.size, caption: req.body.caption });
});
app.use((err, req, res, next) => {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(413).json({ error: 'File too large' });
res.status(err.status ?? 500).json({ error: err.message });
});| multer method | Accepts |
|---|---|
upload.single('avatar') |
one file from field avatar → req.file |
upload.array('photos', 5) |
up to 5 files from one field → req.files |
upload.fields([...]) |
several named fields → req.files.<name> |
upload.none() |
text fields only |
Sending a file from a client
curl -F "caption=My new avatar" -F "avatar=@me.png;type=image/png" http://localhost:3000/avatars
curl -F "avatar=@notes.txt;type=text/plain" http://localhost:3000/avatars{"stored":"5f0c2a9e1d7b44c3a8e6f1b2c3d4e5f6","size":48213,"caption":"My new avatar"}
{"error":"Only PNG, JPEG or WebP images"}
From browser JavaScript, build a FormData — and don't set Content-Type yourself; the browser adds it with the boundary:
const form = new FormData();
form.append('caption', 'My new avatar');
form.append('avatar', fileInput.files[0]);
await fetch('/avatars', { method: 'POST', body: form });Without a library: raw bodies
If a client sends just the file bytes (with a proper Content-Type), express.raw() gives you a Buffer — no multipart needed. This is common for API-to-API uploads and is fully runnable:
const express = require('express');
const app = express();
const stored = new Map();
app.put('/files/:name',
express.raw({ type: ['image/*', 'application/pdf'], limit: '1mb' }),
(req, res) => {
if (!Buffer.isBuffer(req.body)) return res.status(415).json({ error: 'Unsupported file type' });
stored.set(req.params.name, { type: req.get('Content-Type'), data: req.body });
res.status(201).json({ name: req.params.name, bytes: req.body.length });
});
app.get('/files/:name', (req, res) => {
const file = stored.get(req.params.name);
if (!file) return res.sendStatus(404);
res.type(file.type).send(file.data);
});
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}/files/`;
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); // PNG signature
let res = await fetch(base + 'logo.png', { method: 'PUT', headers: { 'Content-Type': 'image/png' }, body: png });
console.log('upload png :', res.status, await res.text());
res = await fetch(base + 'notes.txt', { method: 'PUT', headers: { 'Content-Type': 'text/plain' }, body: 'hi' });
console.log('upload txt :', res.status, await res.text());
res = await fetch(base + 'logo.png');
const bytes = Buffer.from(await res.arrayBuffer());
console.log('download :', res.status, res.headers.get('content-type'), bytes.toString('hex'));
server.close();
});upload png : 201 {"name":"logo.png","bytes":8}
upload txt : 415 {"error":"Unsupported file type"}
download : 200 image/png 89504e470d0a1a0a
Security checklist
| Risk | Defence |
|---|---|
| huge files fill the disk or memory | limits.fileSize, a max file count, and a proxy body-size limit |
path traversal via ../../etc/passwd filenames |
never use originalname as a path; generate your own names |
fake types (.png that's really a script) |
check the declared type and the file's magic bytes; never serve uploads as HTML |
| executing uploaded files | store outside the code folder; serve with Content-Disposition: attachment |
| malware | scan files if users share them with others |
Tip: For large files or many users, skip your server entirely: the API hands the client a short-lived pre-signed URL for object storage (Amazon S3, Google Cloud Storage, Cloudflare R2), and the browser uploads directly there. Your server only stores the resulting object key.
Test yourself
Which content type do HTML forms use to upload files?
- application/json
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
With multer's upload.single('avatar'), where is the uploaded file's info?
- req.body.avatar
- req.file
- req.files.avatar
- res.locals.file
Why shouldn't you save uploads under the client's original filename?
- Filenames are too long
- They may contain path tricks like
../or clash with other files - Express forbids it
- It slows down uploads