File uploads are a common feature in most web applications. In this tutorial, we’ll learn how to upload files like images and videos using Multer in Node.js and Express. Multer simplifies handling file uploads by managing multipart/form-data, which is used for uploading files.
What is Multer in Node.js?
Multer is a middleware for Node.js that simplifies handling file uploads. It’s built on top of the busboy library, making it efficient for uploading files to the server.
With Multer, you can:
- Rename files during the upload
- Set file size limits
- Filter files by types (like images or videos)
Let’s dive into how we can set up file uploads using Multer.
Step-by-Step Guide to File Upload with Multer in Node.js
Step 1: Initial Setup
First, we need to set up our project. Here’s how:
- Create a project folder:
mkdir MulterApp
cd MulterApp
- Initialize Node project:
npm init -y
- Install dependencies: We’ll need Express for the server and Multer for file uploads.
npm install express multer
Step 2: Set Up Express Server
In your app.js, add the following basic Express setup:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, welcome to file upload!');
});
app.listen(port, () => {
console.log('Server running on port ' + port);
});
Now, run your server with:
node app.js
Visit http://localhost:3000
to see the server running.
Step 3: Add Multer for File Upload
Let’s configure Multer to handle file uploads.
- Create a folder for storing uploaded files (e.g., “images”).
- Add the Multer configuration in app.js to define the storage and file naming.
const multer = require('multer');
const path = require('path');
// Setup Multer storage for images
const imageStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images'); // Folder to store images
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname));
}
});
// Create upload function with limits and file type validation
const imageUpload = multer({
storage: imageStorage,
limits: { fileSize: 1000000 }, // Max size 1MB
fileFilter: (req, file, cb) => {
if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
return cb(new Error('Only image files are allowed'));
}
cb(null, true);
}
});
Step 4: Create POST Route for Image Upload
Now, let’s set up the route to handle file uploads. When a user uploads a file, it will be saved to the images folder.
// Handle single image upload
app.post('/uploadImage', imageUpload.single('image'), (req, res) => {
res.send(req.file); // Send the file details back
}, (error, req, res, next) => {
res.status(400).send({ error: error.message });
});
You can test this in Postman by sending a POST request to http://localhost:3000/uploadImage
and uploading an image. You should see the image details as a response.
Step 5: Upload Multiple Images with Multer
Multer can also handle multiple files with the array
function. Here’s how:
app.post('/uploadBulkImage', imageUpload.array('images', 4), (req, res) => {
res.send(req.files); // Send details of all uploaded files
}, (error, req, res, next) => {
res.status(400).send({ error: error.message });
});
This will allow the upload of multiple images, up to a maximum of 4 files. The uploaded files will be saved in the images folder.
Step 6: Upload Videos with Multer
Let’s now look at uploading video files. We’ll set up another storage configuration for videos:
// Setup Multer for video uploads
const videoStorage = multer.diskStorage({
destination: 'videos', // Store videos in the 'videos' folder
filename: (req, file, cb) => {
cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname));
}
});
const videoUpload = multer({
storage: videoStorage,
limits: { fileSize: 10000000 }, // Max size 10MB
fileFilter: (req, file, cb) => {
if (!file.originalname.match(/\.(mp4|mkv)$/)) {
return cb(new Error('Only mp4 or mkv video files are allowed'));
}
cb(null, true);
}
});
// POST route for video upload
app.post('/uploadVideo', videoUpload.single('video'), (req, res) => {
res.send(req.file); // Return the uploaded video details
}, (error, req, res, next) => {
res.status(400).send({ error: error.message });
});
Step 7: Testing the Upload
- For images, use the
/uploadImage
route. - For multiple images, use the
/uploadBulkImage
route. - For videos, use the
/uploadVideo
route.
Conclusion
In this tutorial, we’ve learned how to use Multer in Node.js to handle file uploads, including images, videos, and multiple files. By leveraging Multer’s capabilities, we can ensure smooth, efficient file management while providing robust security features, such as file type validation and size restrictions.
At SvayambhuTech, we specialize in building high-performance applications, including seamless file upload integrations, using technologies like Node.js and Express. If you need expert guidance or assistance in setting up file uploads or building custom web solutions, our experienced team is here to help. We offer cutting-edge development services to ensure your project is completed efficiently and to the highest standards.
Ready to take your project to the next level? Contact SvayambhuTech today, and let’s build something great together!
Happy Coding!