Handling File Uploads in Node.js with Multer
File uploads are an essential feature for many web applications, enabling users to upload profile pictures, documents, and other files. In a Node.js application, handling file uploads can be efficiently managed using Multer, a middleware for Express.js.
What is Multer?
Multer is a Node.js middleware designed for handling multipart/form-data, primarily used for uploading files. It simplifies the process of receiving and processing files from users via forms.
Installing Multer
To use Multer, you need to install it via npm:
npm install multer --save
Setting Up Multer
To get started, import Multer into your Node.js project and configure it.
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
// Configure storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// File upload route
app.post('/upload', upload.single('file'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
res.send(`File uploaded successfully: ${req.file.filename}`);
});
app.listen(3000, () => console.log('Server started on port 3000'));
Understanding the Code
multer.diskStorage
: Specifies the storage destination and filename structure.upload.single('file')
: Handles a single file upload with the field namefile
.- Upload Directory: Files will be stored in the
uploads/
folder.
Handling Multiple File Uploads
Multer also allows multiple file uploads:
app.post('/upload-multiple', upload.array('files', 5), (req, res) => {
res.send(`Uploaded ${req.files.length} files successfully.`);
});
Here, up to 5 files can be uploaded at once.
Filtering Files (MIME Type Validation)
To restrict uploads to specific file types, use a filter:
const fileFilter = (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Only images are allowed'), false);
}
};
const uploadWithFilter = multer({ storage, fileFilter });
Conclusion
Multer simplifies file handling in Node.js, making it easy to store, validate, and process uploads. Whether you’re building an image upload feature or handling document submissions, Multer is a reliable and efficient solution.
Happy coding!