Multer is a middleware used to handle multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy library and integrates easily with Express.js.
Follow these steps:
npm install multermulter.diskStorage()When you need to accept and store files sent via an HTML form or an API request (like image uploads in a profile form or documents in a resume upload form).
// server.js
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
// Storage configuration
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // Upload folder
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // Rename with timestamp
}
});
// Multer middleware
const upload = multer({ storage: storage });
// POST Route
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded successfully!');
});
app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>