Express · Lesson 8 of 15
File Uploads with Multer
Accept multipart files, cap size and write to disk or S3.
- Intermediate
- 14 min read
- 3 objectives
Before this lessonLesson 7: Sessions, Cookies and CSRF
What you will learn
- Use multer
- Limit size and type
- Return a public URL
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Multer parses multipart/form-data. Combine it with size limits and an allow-list of MIME types.
Disk storage
import multer from "multer";
import { randomUUID } from "node:crypto";
import path from "node:path";
const upload = multer({
storage: multer.diskStorage({
destination: "uploads/",
filename: (_req, file, cb) => cb(null, randomUUID() + path.extname(file.originalname)),
}),
limits: { fileSize: 5 * 1024 * 1024 },
fileFilter: (_req, file, cb) => {
cb(null, ["image/jpeg", "image/png", "application/pdf"].includes(file.mimetype));
},
});
app.post("/files", upload.single("file"), (req, res) => {
if (!req.file) return res.status(400).json({ error: "file required" });
res.status(201).json({ name: req.file.filename, size: req.file.size });
});On a multi-instance host, disk is the wrong destination. Stream to S3 with @aws-sdk/client-s3 and store only the key.
