A Complete Guide to Handling File Uploads With Multer in Node.js
A Complete Guide to Handling File Uploads With Multer in Node.js Learn how to implement robust file upload functionality in a Node.js backend using the Multer middleware. Introduction When building APIs or fullstack applications, handling file uploads is a common requirement. In the Node.js ecosystem, Multer is the most popular middleware for handling multipart/form-data, especially for uploading files. This guide walks you through how to use Multer with Express, covering single file uploads, multiple uploads, and file validation. Step 1: Set Up a New Node.js Project Initialize a new project directory: mkdir multer-upload-example cd multer-upload-example npm init -y npm install express multer Step 2: Create Your Express Server Create a file named server.js and add the following basic server setup: const express = require('express'); const multer = require('multer'); const app = express(); const port = 3000; app.listen(port, () => { console.log(`Server listening on port ${port}`); }); Step 3: Configure Multer Storage You can configure Multer to control where and how files are stored. Use diskStorage for local file storage: const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads/'); }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); cb(null, uniqueSuffix + '-' + file.originalname); } }); const upload = multer({ storage: storage }); Create an uploads directory in your root folder: mkdir uploads Step 4: Handle a Single File Upload Add a route that handles uploading a single file using Multer: app.post('/upload-single', upload.single('file'), (req, res) => { res.send({ message: 'File uploaded successfully!', file: req.file }); }); Step 5: Handle Multiple File Uploads To accept multiple files from the same input field: app.post('/upload-multiple', upload.array('files', 5), (req, res) => { res.send({ message: 'Files uploaded successfully!', files: req.files }); }); Step 6: Add File Type and Size Validation Prevent invalid files by filtering MIME types and setting file size limits: const uploadWithValidation = multer({ storage: storage, limits: { fileSize: 5 * 1024 * 1024 }, // 5MB fileFilter: function (req, file, cb) { if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') { cb(null, true); } else { cb(new Error('Only .png and .jpg files are allowed!')); } } }); Use this middleware the same way: app.post('/upload-validated', uploadWithValidation.single('file'), (req, res) => { res.send({ message: 'Validated file uploaded!', file: req.file }); }); Conclusion Multer is a powerful and flexible middleware that simplifies file handling in Node.js. Whether you're storing files locally or uploading them to a cloud storage provider, Multer gives you control over file naming, size limits, and validation. As next steps, you could integrate Multer with a service like AWS S3 or Cloudinary for production-ready file management. Found this guide helpful? You can support my writing at buymeacoffee.com/hexshift.
A Complete Guide to Handling File Uploads With Multer in Node.js
Learn how to implement robust file upload functionality in a Node.js backend using the Multer middleware.
Introduction
When building APIs or fullstack applications, handling file uploads is a common requirement. In the Node.js ecosystem, Multer is the most popular middleware for handling multipart/form-data
, especially for uploading files.
This guide walks you through how to use Multer with Express, covering single file uploads, multiple uploads, and file validation.
Step 1: Set Up a New Node.js Project
Initialize a new project directory:
mkdir multer-upload-example
cd multer-upload-example
npm init -y
npm install express multer
Step 2: Create Your Express Server
Create a file named server.js
and add the following basic server setup:
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Step 3: Configure Multer Storage
You can configure Multer to control where and how files are stored. Use diskStorage
for local file storage:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + '-' + file.originalname);
}
});
const upload = multer({ storage: storage });
Create an uploads
directory in your root folder:
mkdir uploads
Step 4: Handle a Single File Upload
Add a route that handles uploading a single file using Multer:
app.post('/upload-single', upload.single('file'), (req, res) => {
res.send({
message: 'File uploaded successfully!',
file: req.file
});
});
Step 5: Handle Multiple File Uploads
To accept multiple files from the same input field:
app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
res.send({
message: 'Files uploaded successfully!',
files: req.files
});
});
Step 6: Add File Type and Size Validation
Prevent invalid files by filtering MIME types and setting file size limits:
const uploadWithValidation = multer({
storage: storage,
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
fileFilter: function (req, file, cb) {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
cb(new Error('Only .png and .jpg files are allowed!'));
}
}
});
Use this middleware the same way:
app.post('/upload-validated', uploadWithValidation.single('file'), (req, res) => {
res.send({ message: 'Validated file uploaded!', file: req.file });
});
Conclusion
Multer is a powerful and flexible middleware that simplifies file handling in Node.js. Whether you're storing files locally or uploading them to a cloud storage provider, Multer gives you control over file naming, size limits, and validation.
As next steps, you could integrate Multer with a service like AWS S3 or Cloudinary for production-ready file management.
Found this guide helpful? You can support my writing at buymeacoffee.com/hexshift.