When building web applications, you may often need to allow users to upload files. This is where Multer comes in! Multer is a middleware for Node.js that simplifies the process of handling file uploads. It makes it easy to manage file storage, naming, and validation. In this article, we’ll explore three diverse practical examples of uploading files using Multer in Node.js. Each example will be accompanied by explanations to help you understand how it works.
In this first example, we’ll create a simple file upload setup where users can upload a single image file. This is useful for applications that require profile pictures or image uploads for posts.
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 3000;
// Set storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init upload
const upload = multer({ storage: storage }).single('myImage');
// Route for uploading file
app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.status(400).send('Error uploading file.');
} else {
res.send('File uploaded successfully!');
}
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
uploads
folder in your project directory to store the uploaded files..single()
to handle a single file upload, which is great for profile pictures.Sometimes, you might want to allow users to upload multiple files at once. This example demonstrates how to set up Multer for handling multiple file uploads, perfect for document submissions or gallery uploads.
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 3000;
// Set storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// Init upload for multiple files
const upload = multer({ storage: storage }).array('myFiles', 5); // limit to 5 files
// Route for uploading files
app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.status(400).send('Error uploading files.');
} else {
res.send('Files uploaded successfully!');
}
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
array()
method is used here, allowing for multiple files. You can adjust the second parameter to set a limit on how many files a user can upload.enctype
attribute: <form enctype="multipart/form-data">
.In this final example, we will implement file type validation. This is especially useful when you want to restrict users to upload only specific types of files, such as images or PDFs.
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 3000;
// Set storage engine
const storage = multer.diskStorage({
destination: './uploads/',
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
});
// File filter for validation
const fileFilter = (req, file, cb) => {
const filetypes = /jpeg|jpg|png|pdf/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb('Error: File upload only supports the following filetypes - ' + filetypes);
}
};
// Init upload with validation
const upload = multer({ storage: storage, fileFilter: fileFilter }).single('myFile');
// Route for uploading file
app.post('/upload', (req, res) => {
upload(req, res, (err) => {
if (err) {
res.status(400).send(err);
} else {
res.send('File uploaded successfully!');
}
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
fileFilter
function checks the file type before uploading. You can modify the regex pattern in filetypes
to allow other file types as needed.These examples provide a solid foundation for implementing file uploads in your Node.js applications using Multer. Whether you need basic uploads, multiple file uploads, or file validation, you now have a clear understanding of how to handle these scenarios effectively in your projects. Happy coding!