Multer
Multer is a Node.js middleware designed for efficiently handling `multipart/form-data`, primarily used for uploading files. It builds on the busboy library for maximum performance and integrates seamlessly with Express. The current stable version is 2.1.1, with recent releases frequently addressing critical security vulnerabilities (CVEs), indicating active and diligent maintenance.
Common errors
-
MulterError: Unexpected field
cause The field name specified in your HTML form's file input does not match the argument provided to Multer's middleware function (e.g., `upload.single('avatar')`).fixVerify that the `name` attribute of your `<input type="file" name="fieldName">` exactly matches the string argument passed to Multer's processing method (e.g., `upload.single('fieldName')`). -
Error: ENOENT: no such file or directory, open 'uploads/...' (or similar file system error)
cause Multer's `dest` option points to a directory that does not exist on the server when a file upload is attempted.fixEnsure the destination directory (e.g., `uploads/`) is created and accessible by your Node.js application before the server starts. You can do this programmatically: `const fs = require('fs'); if (!fs.existsSync('uploads')) fs.mkdirSync('uploads');`. -
TypeError: Cannot read properties of undefined (reading 'originalname')
cause `req.file` (or an element in `req.files`) is undefined in your route handler, typically because no file was uploaded, the file field name was incorrect, or the form's `enctype` was not `multipart/form-data`.fixConfirm that the HTML form has `enctype="multipart/form-data"`, the file input has a `name` attribute matching Multer's middleware, and a file was actually selected for upload. Add checks for `if (req.file)` before accessing its properties. -
MulterError: File too large
cause The uploaded file's size exceeds the `fileSize` limit configured in Multer's options (`limits.fileSize`).fixIncrease the `fileSize` limit within Multer's configuration, e.g., `multer({ limits: { fileSize: 5 * 1024 * 1024 } })` for a 5MB limit. Alternatively, inform the user about the maximum allowed file size.
Warnings
- breaking Multer v2.0.0 and subsequent versions require Node.js version 10.16.0 or higher.
- gotcha Multer exclusively processes `multipart/form-data` content types. It will not parse forms submitted with `application/x-www-form-urlencoded`, `application/json`, or other content types, leaving `req.body` empty for non-file fields.
- gotcha When using `multer({ dest: 'uploads/' })`, files are stored in the specified directory without their original file extensions. They will also have generic names.
- gotcha Access to `req.file`, `req.files`, and the parsed `req.body` (for text fields) is only available *after* the Multer middleware has successfully processed the request.
Install
-
npm install multer -
yarn add multer -
pnpm add multer
Imports
- multer
const multer = require('multer')
Quickstart
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
// Ensure the 'uploads' directory exists
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
// Configure Multer storage
const upload = multer({ dest: uploadDir });
const app = express();
// Route to handle single file upload
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
if (req.file) {
console.log(`File uploaded: ${req.file.originalname} (${req.file.mimetype})`);
console.log(`Saved to: ${req.file.path}`);
} else {
console.log('No file uploaded.');
}
if (Object.keys(req.body).length > 0) {
console.log('Form data:', req.body);
}
res.send('File upload processed!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));