Node.jsExpressError Fix2026 Updated

Node.js File Upload Error— Fixed [Complete Guide 2026]

January 20266 min readNode.js · multer · All OS

⚡ Complete Working Upload Setup

terminal
npm install multer
server.js
const 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 / SymptomFix
req.file is undefinedFix 2 — field name mismatch or missing middleware
LIMIT_FILE_SIZEFix 3 — increase size limit
LIMIT_UNEXPECTED_FILEFix 2 — wrong field name
MulterError: Non-string fieldFix 7 — frontend not using FormData
File saved but wrong extensionFix 5 — use diskStorage for filenames
413 Payload Too LargeFix 3 — increase express + multer limits
1

Install and Configure multer

Complete working setup
3 min
routes/upload.js
const 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 = router
2

Fix req.file undefined

Most common upload issue
2 min

req.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.

Diagnose — log the request
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
})
Frontend — field name must match
// 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.

3

Set File Size Limits

LIMIT_FILE_SIZE / 413 errors
2 min
server.js
const 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' }))
4

Validate File Types (MIME Types)

Only allow images / PDFs / specific types
3 min
server.js
const 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.

5

Control Filenames on Disk (diskStorage)

Custom filenames and directories
3 min

By default, multer saves files with random names and no extension. Use diskStorage for full control over filenames.

server.js
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 } })
6

Upload to AWS S3 / Cloudinary

Production — cloud storage
10 min

AWS S3 with multer-s3

terminal
npm install multer-s3 @aws-sdk/client-s3
server.js
const { 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.

7

Frontend FormData — Send Files Correctly

Common frontend mistakes that cause upload errors
2 min
Frontend — correct file upload
// ✅ 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

Frequently Asked Questions

How do I handle file uploads in Node.js Express?+
Install multer: npm install multer. Then: const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), (req, res) => { console.log(req.file); res.json({ path: req.file.path }) }). The field name in upload.single() must match your frontend input name.
Why is req.file undefined in Express?+
Most common causes: 1) The frontend is not using FormData or is setting Content-Type manually (don't), 2) The field name in upload.single('field') doesn't match your form input name, 3) The multer middleware is not applied to the route.
How do I limit upload file size in multer?+
Pass limits: { fileSize: 5 * 1024 * 1024 } to multer: const upload = multer({ dest: 'uploads/', limits: { fileSize: 5 * 1024 * 1024 } }). Handle the error in your route to send a proper 413 response.
How do I validate file types in multer?+
Use the fileFilter option: const upload = multer({ fileFilter: (req, file, cb) => { if (!file.mimetype.startsWith('image/')) { return cb(new Error('Only images allowed')) } cb(null, true) } })
multer LIMIT_FILE_SIZE error — how to fix?+
Your uploaded file exceeds multer's size limit. Either increase the limit in multer config: limits: { fileSize: 10 * 1024 * 1024 } or return a helpful 413 error to the user.
How do I upload files to S3 instead of local disk?+
Use multer-s3: npm install multer-s3 @aws-sdk/client-s3. Configure multer with multer-s3 storage engine pointing to your S3 bucket. Files will upload directly to S3 without touching your server's 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