Node.js File Upload Error— Fixed [Complete Guide 2026]
⚡ Complete Working Upload Setup
npm install multerconst multer = require('multer')
const upload = multer({ dest: 'uploads/' })
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file uploaded' })
res.json({ path: req.file.path, name: req.file.originalname })
})Common File Upload Errors
| Error / Symptom | Fix |
|---|---|
| req.file is undefined | Fix 2 — field name mismatch or missing middleware |
| LIMIT_FILE_SIZE | Fix 3 — increase size limit |
| LIMIT_UNEXPECTED_FILE | Fix 2 — wrong field name |
| MulterError: Non-string field | Fix 7 — frontend not using FormData |
| File saved but wrong extension | Fix 5 — use diskStorage for filenames |
| 413 Payload Too Large | Fix 3 — increase express + multer limits |
Install and Configure multer
Complete working setupconst express = require('express')
const multer = require('multer')
const path = require('path')
const fs = require('fs')
const router = express.Router()
// Ensure upload directory exists
const uploadDir = path.join(__dirname, '..', 'uploads')
fs.mkdirSync(uploadDir, { recursive: true })
// Basic setup — multer saves files with random names
const upload = multer({
dest: uploadDir,
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
})
// Single file
router.post('/single', upload.single('file'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file received' })
res.json({
message: 'Upload successful',
filename: req.file.filename,
originalName: req.file.originalname,
size: req.file.size,
mimetype: req.file.mimetype,
path: req.file.path,
})
})
// Multiple files (up to 10)
router.post('/multiple', upload.array('files', 10), (req, res) => {
if (!req.files?.length) return res.status(400).json({ error: 'No files received' })
res.json({ uploaded: req.files.length, files: req.files.map(f => f.originalname) })
})
module.exports = routerFix req.file undefined
Most common upload issuereq.file is undefined when the field name in upload.single('fieldname') does not match the field name your frontend sends, or when multer middleware is not applied.
app.post('/upload', upload.single('file'), (req, res) => {
console.log('Body:', req.body) // form text fields
console.log('File:', req.file) // file info or undefined
console.log('Files:', req.files) // for array uploads
})// Backend: upload.single('avatar')
// Frontend must use the SAME field name: 'avatar'
const formData = new FormData()
formData.append('avatar', fileInput.files[0]) // ← 'avatar' matches
fetch('/upload', { method: 'POST', body: formData })Never set Content-Type manually when using FormData. The browser automatically adds multipart/form-data with the correct boundary. Setting it manually breaks the upload.
Set File Size Limits
LIMIT_FILE_SIZE / 413 errorsconst upload = multer({
dest: 'uploads/',
limits: {
fileSize: 10 * 1024 * 1024, // 10MB in bytes
files: 5, // max 5 files per request
}
})
// Handle multer errors in your route
app.post('/upload', (req, res, next) => {
upload.single('file')(req, res, (err) => {
if (err instanceof multer.MulterError) {
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: 'File too large. Maximum 10MB allowed.' })
}
return res.status(400).json({ error: err.message })
} else if (err) {
return res.status(500).json({ error: err.message })
}
if (!req.file) return res.status(400).json({ error: 'No file uploaded' })
res.json({ path: req.file.path })
})
})
// Also increase Express body limit if needed
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true, limit: '10mb' }))Validate File Types (MIME Types)
Only allow images / PDFs / specific typesconst upload = multer({
dest: 'uploads/',
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
// Allow only images
if (!file.mimetype.startsWith('image/')) {
return cb(new Error('Only image files are allowed'))
}
cb(null, true)
}
})
// Allow specific types
const allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf']
const upload = multer({
fileFilter: (req, file, cb) => {
if (!allowedTypes.includes(file.mimetype)) {
return cb(new Error(`File type ${file.mimetype} not allowed`))
}
cb(null, true)
}
})Never trust the file extension alone. Always check file.mimetype which is set by the browser. For stronger security, use the 'file-type' package to check actual file magic bytes.
Control Filenames on Disk (diskStorage)
Custom filenames and directoriesBy default, multer saves files with random names and no extension. Use diskStorage for full control over filenames.
const storage = multer.diskStorage({
destination: (req, file, cb) => {
// Save to different folders based on file type
const dir = file.mimetype.startsWith('image/')
? path.join(__dirname, 'uploads', 'images')
: path.join(__dirname, 'uploads', 'documents')
fs.mkdirSync(dir, { recursive: true })
cb(null, dir)
},
filename: (req, file, cb) => {
// Unique filename: timestamp + original extension
const ext = path.extname(file.originalname)
const basename = path.basename(file.originalname, ext)
const unique = Date.now() + '-' + Math.round(Math.random() * 1e9)
cb(null, `${basename}-${unique}${ext}`)
// → profile-photo-1706789012345-123456789.jpg
}
})
const upload = multer({ storage, limits: { fileSize: 5 * 1024 * 1024 } })Upload to AWS S3 / Cloudinary
Production — cloud storageAWS S3 with multer-s3
npm install multer-s3 @aws-sdk/client-s3const { S3Client } = require('@aws-sdk/client-s3')
const multerS3 = require('multer-s3')
const s3 = new S3Client({ region: process.env.AWS_REGION })
const upload = multer({
storage: multerS3({
s3,
bucket: process.env.S3_BUCKET,
contentType: multerS3.AUTO_CONTENT_TYPE,
key: (req, file, cb) => {
const key = `uploads/${Date.now()}-${file.originalname}`
cb(null, key)
},
}),
limits: { fileSize: 10 * 1024 * 1024 },
})
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ url: req.file.location }) // S3 URL
})Store AWS credentials in .env: AWS_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, S3_BUCKET. Never hardcode them in source code.
Frontend FormData — Send Files Correctly
Common frontend mistakes that cause upload errors// ✅ CORRECT — using FormData
const formData = new FormData()
formData.append('file', fileInput.files[0])
formData.append('description', 'My photo') // text fields work too
// Do NOT set Content-Type manually — browser sets it automatically
const response = await fetch('/upload', {
method: 'POST',
body: formData,
// ❌ Do NOT add: headers: { 'Content-Type': 'multipart/form-data' }
})
// ✅ Axios — also works with FormData
const res = await axios.post('/upload', formData)
// Axios automatically sets the correct Content-Type
// ✅ React — handling file input
function UploadForm() {
const handleSubmit = async (e) => {
e.preventDefault()
const file = e.target.file.files[0]
const form = new FormData()
form.append('file', file)
await fetch('/upload', { method: 'POST', body: form })
}
return (
<form onSubmit={handleSubmit}>
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
)
}How to Prevent File Upload Errors
- Always create the upload directory before starting: fs.mkdirSync(uploadDir, { recursive: true })
- Never set Content-Type manually when using FormData
- Match field name in upload.single('name') exactly with frontend form field name
- Always validate MIME types with fileFilter
- Set reasonable size limits — both in multer and express body-parser
- Use diskStorage for predictable filenames with extensions
- In production — upload to S3 or Cloudinary, not server disk
Frequently Asked Questions
How do I handle file uploads in Node.js Express?+−
Why is req.file undefined in Express?+−
How do I limit upload file size in multer?+−
How do I validate file types in multer?+−
multer LIMIT_FILE_SIZE error — how to fix?+−
How do I upload files to S3 instead of local disk?+−
Need Expert Help?
We Build Production-Grade Node.js Apps
Softplix builds full-stack applications. Need help with file uploads, S3 integration, or media handling? We can help.
Talk to an Engineer