How to upload files in Node.js
Handling file uploads is essential for Node.js applications that manage user-generated content, documents, or media files. As the creator of CoreUI with over 11 years of Node.js development experience since 2014, I’ve implemented file upload systems in countless enterprise applications. The most effective solution is to use Multer middleware with Express to handle multipart form data and file storage. This approach is robust, configurable, and provides full control over file validation and storage.
Use Multer middleware to handle file uploads in Node.js.
const express = require('express')
const multer = require('multer')
const path = require('path')
const app = express()
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/')
},
filename: (req, file, cb) => {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage,
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowedTypes = /jpeg|jpg|png|pdf/
const isValid = allowedTypes.test(path.extname(file.originalname).toLowerCase())
isValid ? cb(null, true) : cb(new Error('Invalid file type'))
}
})
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' })
}
res.json({
message: 'File uploaded successfully',
filename: req.file.filename,
path: req.file.path
})
})
First, install Multer with npm install multer. The diskStorage configuration defines where and how files are saved. The filename function creates unique filenames to prevent collisions. File size limits and type validation are configured in the multer options. The upload.single('file') middleware processes the upload and adds file information to req.file. The file field name must match the form field name used by the client.
Best Practice Note
This is the same file upload approach we use in CoreUI backend systems for secure file handling. Always validate file types and sizes on the server, never trust client-side validation. Store uploaded files outside the public directory and serve them through controlled endpoints to prevent security vulnerabilities.



