multer
FIle Upload
Express File Uploads: Theory and Implementation
1. The Theory: Multipart Data
Theory: Standard Express middleware (like express.json()) cannot parse filesmultipart/form-data request
Multer: This middleware acts as a specialized parser that identifies file streams, saves them to a destination, and attaches the file metadata to the
reqobject for your controller to use.
2. Storage Strategies: Disk vs. Memory
Disk Storage (Local)
Theory: Files are written directly to your server's hard drive
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Destination folder
},
filename: (req, file, cb) => {
// Theory: Use timestamps to prevent overwriting files with the same name
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, file.fieldname + '-' + uniqueSuffix);
}
});Memory Storage (Cloud-Ready)
Theory: The file is kept in the server's RAM as a Buffer
3. Validation: The Security Layer
Theory: Never trust a file upload without validation
File Filter: Checks the
mimetypeto ensure the file is an image, PDF, etc. Limits: Restricts the
fileSizeto prevent users from crashing your server with 1GB files.
const upload = multer({
storage,
limits: { fileSize: 2 * 1024 * 1024 }, // 2MB Limit
fileFilter: (req, file, cb) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('Invalid file type!'), false);[cite: 1]
}
}
});4. The Request Lifecycle with Multer
The Process:
Client: Sends a
POSTrequest with a file attached to the field name'avatar'. Multer Middleware: Intercepts the request, validates the size/type, renames the file, and saves it
. Controller: Receives
req.file(single) orreq.files(multiple) containing the path or buffer. Response: The controller sends back the URL where the file can be accessed
.
Single Fileupload.single('fieldname')
Used for profile pictures or single document uploads
Multiple Filesupload.array('fieldname', max)
Used for gallery uploads or multi-page applications
Static Accessexpress.static('folder')
Makes the local folder publicly accessible via a URL[cite: 1].
Cloud Integrationmulter.memoryStorage()
Essential for serverless or scalable cloud architectures[cite: 1].