Node.js 33 🟢 File Upload Handling with Multer
The previous chapter covered request body parsing for JSON, URL-encoded, and raw content types. The multipart/form-data format—the one the browser uses for file uploads—is a separate problem. It is a binary format with boundaries, headers per part, and file streams. Express does not parse it, and the built-in parsers do not touch it. The multer middleware is the standard tool for parsing it: it reads the multipart stream, separates the text fields from the file parts, and stores the files according to a storage engine. This chapter covers Multer in full: installation, the storage engines, the upload methods, validation, error handling, and the security considerations that make file uploads one of the riskiest features in any web application.
Key point: Multer is middleware for multipart/form-data. It populates req.body with the text fields and req.file or req.files with the uploaded files. The storage engine determines where the files go: diskStorage writes them to the filesystem, memoryStorage keeps them in a Buffer in memory. The upload method determines how many files are accepted: .single(), .array(), .fields(), .none(), or .any(). The limits option caps the file size and count. The fileFilter option rejects the files that do not match the allowed types. The MulterError is not caught by the default error handler; an explicit error handler is required.
Why Multer exists
The multipart problem. A request with enctype="multipart/form-data" contains multiple parts, each with its own headers. A part can be a text field or a file. The file part has a filename, a content type, and a binary body. Parsing this format requires a streaming parser that handles the boundaries, the headers, and the binary data. Multer wraps the busboy parser and provides the Express middleware interface .
The storage problem. The uploaded file needs to go somewhere. The diskStorage writes it to the filesystem and returns the path. The memoryStorage keeps it in memory as a Buffer. The choice determines how the file is accessed after the upload and whether the application can run out of memory .
The validation problem. The file is untrusted. Its MIME type, its extension, and its contents can be malicious. The fileFilter rejects the files that do not match the allowed types. The limits option caps the size and the count. The validation is the first line of defense, and it must run before the file is stored .
The cleanup problem. When an upload fails, or when the application errors after the upload, the file may be left on the disk. The storage engine’s _removeFile method removes it. The error handler calls the cleanup. Without it, the abandoned files accumulate and exhaust the disk .
The security problem. A file upload is a direct path for the malicious content into the server. The filename can contain the path traversal sequences (../). The MIME type can be spoofed. The file content can be a script, a virus, or a zip bomb. The upload handling must validate the type, sanitize the name, store the file outside the web root, and scan the content .
The compatibility problem. Multer is the standard, but it is not the only option. The express-fileupload package is an alternative with a simpler API. The formidable package is another. The Multer is the most widely used and the one with the largest ecosystem .
a. Installation and basic setup
Multer is installed with npm.
npm install multer
The middleware is created with multer(opts). The options object configures the storage engine, the limits, and the file filter.
const express = require('express')
const multer = require('multer')
const app = express()
const upload = multer({ dest: 'uploads/' })
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file)
console.log(req.body)
res.json({ file: req.file })
})
The dest: 'uploads/' is the simplest configuration. Multer creates the directory if it does not exist and writes the files there with random names . The req.file is the file object with the metadata. The req.body is the text fields.
The file object has the properties:
| Property | Description |
|---|---|
fieldname | The form field name |
originalname | The name on the user’s computer |
encoding | The encoding type |
mimetype | The MIME type |
size | The size in bytes |
destination | The folder (diskStorage) |
filename | The name in the destination (diskStorage) |
path | The full path (diskStorage) |
buffer | The file content (memoryStorage) |
The originalname is client-supplied and must be treated as untrusted .
The dest option is the shortcut. The storage option is the full control.
b. The storage engines
Multer ships with two storage engines: diskStorage and memoryStorage .
diskStorage writes the files to the filesystem. It is configured with the destination and the filename functions.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/')
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
}
})
const upload = multer({ storage })
The destination determines the folder. The filename determines the name within the folder. Multer does not append the extension; the filename function must include it . The unique suffix prevents the collisions when multiple files have the same original name .
The destination can be a string or a function. If it is a string, Multer creates the directory if it does not exist . If it is a function, the function is responsible for the creation.
memoryStorage keeps the files in memory as Buffer objects.
const storage = multer.memoryStorage()
const upload = multer({ storage })
The file is in req.file.buffer. The memory storage is for the cases where the file is processed in memory and not saved to disk: the image resizing, the parsing, the forwarding to a cloud storage service . The warning is the memory: a large file, or many files, can exhaust the process memory .
The custom storage engines implement _handleFile and _removeFile. The _handleFile receives the file stream, stores it, and returns the file information. The _removeFile removes the file when the request fails .
c. The upload methods, validation, and errors
The upload method determines how many files are accepted and where they are stored.
| Method | Files | req Property |
|---|---|---|
.single('field') | One file | req.file |
.array('field', max) | Multiple, same field | req.files (array) |
.fields([...]) | Multiple, different fields | req.files (object) |
.none() | No files, text only | — |
.any() | Any files | req.files (array) |
The .single('avatar') accepts one file with the field name avatar. The file is in req.file .
The .array('photos', 5) accepts up to five files with the field name photos. The files are in req.files as an array .
The .fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) accepts the multiple fields. The files are in req.files as an object with the field names as the keys .
The .none() accepts only the text fields. A file upload produces the LIMIT_UNEXPECTED_FILE error .
The .any() accepts all the files. The warning is the security: never use it as a global middleware, and always handle the files on the routes where they are expected .
The validation is configured with the limits and the fileFilter.
const upload = multer({
storage,
limits: {
fileSize: 5 * 1024 * 1024,
files: 5
},
fileFilter: (req, file, cb) => {
const allowed = ['image/jpeg', 'image/png', 'application/pdf']
if (allowed.includes(file.mimetype)) {
cb(null, true)
} else {
cb(new Error('Invalid file type'))
}
}
})
The limits.fileSize caps the size. The limits.files caps the count. The fileFilter rejects the types. The validation checks both the MIME type and the extension to prevent the spoofing .
The errors are the MulterError instances. The error handler checks the err.code.
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'File too large' })
}
if (err.code === 'LIMIT_FILE_COUNT') {
return res.status(400).json({ error: 'Too many files' })
}
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
return res.status(400).json({ error: 'Unexpected file field' })
}
}
next(err)
})
The MulterError is not caught by the default Express error handler. The explicit error handler is required .
The cleanup is the handling of the files when the request fails after the upload.
app.post('/profile', upload.single('avatar'), async (req, res) => {
try {
await db.save(req.file.path)
res.json({ success: true })
} catch (err) {
fs.unlink(req.file.path, () => {})
res.status(500).json({ error: 'Failed' })
}
})
The fs.unlink removes the file when the database operation fails. The pattern is the manual cleanup. The clean-up-after-multer middleware automates it .
Complete Example Session
// ============================================
// PART 1: BASIC SETUP
// ============================================
const express = require('express')
const multer = require('multer')
const path = require('path')
const app = express()
const upload = multer({ dest: 'uploads/' })
// ============================================
// PART 2: DISK STORAGE WITH CUSTOM NAME
// ============================================
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => {
const unique = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + unique + path.extname(file.originalname))
}
})
const upload = multer({ storage })
// ============================================
// PART 3: MEMORY STORAGE
// ============================================
const upload = multer({ storage: multer.memoryStorage() })
app.post('/process', upload.single('file'), (req, res) => {
const buffer = req.file.buffer
res.json({ size: buffer.length })
})
// ============================================
// PART 4: SINGLE FILE UPLOAD
// ============================================
app.post('/upload', upload.single('avatar'), (req, res) => {
res.json({ file: req.file, body: req.body })
})
// ============================================
// PART 5: MULTIPLE FILES
// ============================================
app.post('/photos', upload.array('photos', 5), (req, res) => {
res.json({ count: req.files.length })
})
// ============================================
// PART 6: MIXED FIELDS
// ============================================
const fields = upload.fields([
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 }
])
app.post('/profile', fields, (req, res) => {
res.json({ avatar: req.files.avatar, gallery: req.files.gallery })
})
// ============================================
// PART 7: VALIDATION WITH FILTER
// ============================================
const fileFilter = (req, file, cb) => {
const allowed = ['image/jpeg', 'image/png']
if (allowed.includes(file.mimetype)) {
cb(null, true)
} else {
cb(new Error('Only JPEG and PNG allowed'))
}
}
const upload = multer({ storage, fileFilter, limits: { fileSize: 5 * 1024 * 1024 } })
// ============================================
// PART 8: ERROR HANDLER
// ============================================
app.use((err, req, res, next) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'File too large' })
}
return res.status(400).json({ error: err.message })
}
next(err)
})
// ============================================
// PART 9: CLEANUP ON FAILURE
// ============================================
app.post('/profile', upload.single('avatar'), async (req, res) => {
try {
await db.save(req.file.path)
res.json({ success: true })
} catch (err) {
fs.unlink(req.file.path, () => {})
res.status(500).json({ error: 'Failed' })
}
})
// ============================================
// PART 10: CUSTOM STORAGE ENGINE
// ============================================
const customStorage = {
_handleFile: (req, file, cb) => {
file.stream.pipe(fs.createWriteStream('/tmp/' + file.originalname))
cb(null, { path: '/tmp/' + file.originalname })
},
_removeFile: (req, file, cb) => {
fs.unlink(file.path, cb)
}
}
The ten parts covered the basic setup, disk storage, memory storage, single upload, multiple uploads, mixed fields, validation, the error handler, cleanup, and a custom storage engine.
Quick Reference
Upload Methods
| Method | Accepts | req Property |
|---|---|---|
.single(field) | One file | req.file |
.array(field, max) | Multiple, same field | req.files (array) |
.fields([...]) | Multiple, different fields | req.files (object) |
.none() | Text only | — |
.any() | Any files | req.files (array) |
Storage Engines
| Engine | File Access | Use Case |
|---|---|---|
diskStorage | req.file.path | Permanent storage |
memoryStorage | req.file.buffer | Processing in memory |
Validation Options
| Option | Purpose |
|---|---|
limits.fileSize | Max file size |
limits.files | Max file count |
fileFilter | Accept/reject by type |
Multer Error Codes
| Code | Meaning |
|---|---|
LIMIT_FILE_SIZE | File too large |
LIMIT_FILE_COUNT | Too many files |
LIMIT_UNEXPECTED_FILE | Unexpected field |
LIMIT_PART_COUNT | Too many parts |
File Object Properties
| Property | Storage |
|---|---|
fieldname | All |
originalname | All |
mimetype | All |
size | All |
path | diskStorage |
buffer | memoryStorage |
Best Practices
✅ Do This:
// Set the size limit
limits: { fileSize: 5 * 1024 * 1024 } // ✅
// Validate the type with fileFilter
fileFilter: (req, file, cb) => { } // ✅
// Use unique filenames
filename: (req, file, cb) => {
cb(null, `${Date.now()}-${file.originalname}`)
} // ✅
// Handle the MulterError
if (err instanceof multer.MulterError) { } // ✅
// Clean up the file on failure
fs.unlink(req.file.path, () => {}) // ✅
// Store the files outside the web root
dest: '/var/uploads/' // ✅
❌ Don’t Do This:
// Don't trust the originalname
req.file.originalname // path traversal possible // ❌
// Don't trust the mimetype
// The client can spoof it // ⚠️
// Don't use .any() as a global middleware
app.use(upload.any()) // security risk // ❌
// Don't forget the error handler
// MulterError is not caught by default // ❌
// Don't use memoryStorage for large files
// The process can run out of memory // ⚠️
// Don't store the files in the web root
dest: 'public/uploads/' // served directly // ⚠️
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
req.file undefined | Wrong field name | Check .single() argument |
LIMIT_FILE_SIZE | File exceeds limit | Increase limit or reject |
LIMIT_UNEXPECTED_FILE | Field not expected | Check .fields() config |
| MulterError unhandled | No error handler | Add explicit handler |
| File left on disk | No cleanup | fs.unlink on error |
| Memory exhaustion | memoryStorage with large files | Use diskStorage |
| Path traversal | Untrusted originalname | Sanitize the filename |
Real-World Examples
1. Avatar Upload
app.post('/avatar', upload.single('avatar'), (req, res) => {
res.json({ path: req.file.path })
})
2. Gallery Upload
app.post('/gallery', upload.array('photos', 10), (req, res) => {
res.json({ count: req.files.length })
})
3. Profile with Avatar and Gallery
const fields = upload.fields([
{ name: 'avatar', maxCount: 1 },
{ name: 'gallery', maxCount: 8 }
])
app.post('/profile', fields, (req, res) => {
res.json({ avatar: req.files.avatar, gallery: req.files.gallery })
})
4. Image Processing
const upload = multer({ storage: multer.memoryStorage() })
app.post('/resize', upload.single('image'), async (req, res) => {
const resized = await sharp(req.file.buffer).resize(200).toBuffer()
res.set('Content-Type', 'image/jpeg').send(resized)
})
5. PDF Upload with Validation
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'application/pdf') cb(null, true)
else cb(new Error('Only PDFs'))
}
const upload = multer({ storage, fileFilter })
6. Cloud Storage Forwarding
const upload = multer({ storage: multer.memoryStorage() })
app.post('/cloud', upload.single('file'), async (req, res) => {
const result = await cloud.upload(req.file.buffer)
res.json({ url: result.url })
})
7. Multiple Different Types
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
const isImage = file.mimetype.startsWith('image/')
const isPdf = file.mimetype === 'application/pdf'
cb(null, isImage || isPdf)
}
})
8. Error Handler
app.use((err, req, res, next) => {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'Too large' })
}
next(err)
})
9. Cleanup Middleware
import { cleanUploadedFilesMiddleware } from '@myrotvorets/clean-up-after-multer'
app.use(cleanUploadedFilesMiddleware())
10. Custom Storage
const storage = {
_handleFile: (req, file, cb) => { /* store */ },
_removeFile: (req, file, cb) => { /* remove */ }
}
Visual
Multer Flow
┌─────────────────────────────────────────────────────────────┐
│ multipart/form-data request │
│ │ │
│ ▼ │
│ Multer middleware │
│ │ │
│ ├── Parse the parts │
│ │ │
│ ├── Text fields ──▶ req.body │
│ │ │
│ └── File parts ──▶ storage engine │
│ │ │
│ ├── diskStorage ──▶ req.file.path │
│ │ │
│ └── memoryStorage ──▶ req.file.buffer │
│ │
│ The route handler receives req.body and req.file(s). │
│ │
└─────────────────────────────────────────────────────────────┘
Storage Engines
┌─────────────────────────────────────────────────────────────┐
│ diskStorage │
│ │
│ File written to the filesystem. │
│ req.file.path, req.file.filename, req.file.destination │
│ Use for permanent storage. │
│ │
├─────────────────────────────────────────────────────────────┤
│ │
│ memoryStorage │
│ │
│ File kept in memory as Buffer. │
│ req.file.buffer │
│ Use for processing before storage. │
│ │
└─────────────────────────────────────────────────────────────┘
Upload Methods
┌─────────────────────────────────────────────────────────────┐
│ .single('avatar') │
│ → req.file (one file) │
│ │
│ .array('photos', 5) │
│ → req.files (array, max 5) │
│ │
│ .fields([...]) │
│ → req.files (object, per field) │
│ │
│ .none() │
│ → text fields only, error on file │
│ │
└─────────────────────────────────────────────────────────────┘
Validation and Errors
┌─────────────────────────────────────────────────────────────┐
│ fileFilter │
│ │ │
│ ├── Accept ──▶ cb(null, true) │
│ │ │
│ └── Reject ──▶ cb(new Error('Invalid')) │
│ │
│ limits │
│ │ │
│ ├── fileSize exceeded ──▶ LIMIT_FILE_SIZE │
│ │ │
│ └── files exceeded ──▶ LIMIT_FILE_COUNT │
│ │
│ The errors are MulterError instances. │
│ The explicit error handler catches them. │
│ │
└─────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Package | multer |
| Middleware | multer(opts) |
| Storage | diskStorage, memoryStorage |
| Single | .single('field') → req.file |
| Array | .array('field', max) → req.files |
| Fields | .fields([...]) → req.files |
| None | .none() → text only |
| Any | .any() → req.files |
| Limit | limits.fileSize, limits.files |
| Filter | fileFilter |
| Error | MulterError |
| Cleanup | fs.unlink or middleware |
Key takeaways:
- Multer parses
multipart/form-data. The built-in Express parsers do not handle the format. Multer populatesreq.bodywith the text fields andreq.fileorreq.fileswith the files . - The storage engine determines where the files go.
diskStoragewrites them to the filesystem and provides thepath.memoryStoragekeeps them in memory as aBuffer. - The upload method determines how many files are accepted.
.single()for one,.array()for multiple with the same field,.fields()for multiple with different fields..none()for text only, and.any()for all files . - The
limitsoption caps the file size and count. ThefileSizelimits the size, and thefileslimits the count. The defaults are unlimited, which is a risk . - The
fileFiltervalidates the file type. It checks the MIME type and can check the extension. The validation runs before the file is stored . - The
MulterErrorrequires an explicit error handler. The default Express error handler does not catch it. The handler checks theerr.codeforLIMIT_FILE_SIZE,LIMIT_FILE_COUNT, andLIMIT_UNEXPECTED_FILE. - The file must be cleaned up on failure. When the request fails after the upload, the file is left on the disk. The
fs.unlinkor the cleanup middleware removes it .
Remember: File uploads are one of the riskiest features in a web application. The file is untrusted, the name is untrusted, and the content is untrusted. Multer handles the parsing and the storage, but the validation and the cleanup are the application’s responsibility. Set the size limit, validate the type, sanitize the name, store the files outside the web root, and clean up on failure. The diskStorage is for the permanent storage, the memoryStorage is for the processing, and the custom storage engine is for the cloud and the databases. And always handle the MulterError; the default handler does not.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!