Introduction
Handling file uploads is a common requirement in many web applications. In Node.js, one of the most popular libraries to manage file uploads is Multer. It is middleware for handling multipart/form-data
, which is used for uploading files.
Why Use Multer?
Multer makes it easy to handle file uploads by parsing incoming request bodies and storing uploaded files directly to disk or memory. It integrates seamlessly with Express and is easy to configure.
Setting Up the Project
Step 1: Initialize Node.js Project
mkdir file-upload-app
cd file-upload-app
npm init -y
Step 2: Install Required Packages
npm install express multer
Basic File Upload Example
Create index.js
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
// Configure storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const upload = multer({ storage: storage });
// File upload route
app.post('/upload', upload.single('myfile'), (req, res) => {
res.send('File uploaded successfully!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Create Upload Directory
mkdir uploads
Testing the Upload
Use tools like Postman or a simple HTML form to test the upload:
action="/upload" method="post" enctype="multipart/form-data">
type="file" name="myfile" />
type="submit">Upload
Conclusion
Multer is a powerful and flexible middleware for handling file uploads in Node.js. With just a few lines of code, you can set up a robust upload system for your web application. For advanced use-cases, Multer also supports file filtering, size limits, and memory storage.
Let me know if you'd like to see an example with multiple file uploads or uploading to cloud storage like Cloudinary!