Multer is middleware for handling multipart/form-data. It populates req.body with text fields and either req.file (for a single file) or req.files (for multiple files) with file information.
Warning: Never use Multer as global middleware. Only apply it to specific routes that require file uploads to prevent malicious users from uploading files to unexpected routes.
const express = require('express')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const app = express()
// Handle a single file named 'avatar'
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the 'avatar' file
// req.body contains text fields
})
// Handle an array of files named 'photos' (max 12)
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is the array of 'photos' files
})
// Handle mixed fields
const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
// req.files is an object (String -> Array) where keys are field names
// e.g., req.files['avatar'][0] -> File
})