Express.js: Building REST APIsLesson 4.5
Serving files and handling multipart uploads in Express
express.static, res.sendFile, multer setup, single and multiple file uploads, file type validation, file size limits, storage engines, serving uploaded files
Serving Static Files and Handling Uploads
Use express.static to serve files from a directory. Use multer for handling file uploads from multipart requests.
app.use('/static', express.static(path.join(__dirname, 'public')));
app.get('/download/report', (req, res) => {
res.sendFile(path.join(__dirname, 'reports', 'q3.pdf'));
});File Uploads with Multer
npm install multerconst multer = require('multer');
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
cb(null, Date.now() + '-' + Math.random().toString(36).slice(2) + ext);
}
});
const upload = multer({
storage,
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowed = ['image/jpeg', 'image/png', 'image/webp'];
cb(null, allowed.includes(file.mimetype));
}
});
app.post('/upload', upload.single('avatar'), (req, res) => {
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
res.json({ path: req.file.path, size: req.file.size });
});