Handling File Uploads in Express with Multer
The Problem: Why file upload is difficult
When users upload things on a website like:
photos πΈ
PDFs π
images πΌοΈ
It does not come like normal text.
Normal data looks like:
{ "name": "Amit" }
But files are different:
they are big
they are not simple text
they come in a special format
Express cannot understand files directly.
Simple Problem
Express can handle text data easily
But it cannot handle files by itself
So we need help.
Solution: We need a helper (Middleware)
Middleware is something that works between:
user request
server response
It helps Express understand special data like files.
What is Multer?
Multer is a tool used in Express to handle file uploads.
Simple meaning:
Multer = a helper that handles files
It does 3 things:
takes file from request
saves file in a folder
gives file info to your code
How file upload works (simple flow)
Step 1:
User selects a file πΈ
Step 2:
Browser sends file to server
Step 3:
Multer receives the file
Step 4:
Multer saves file in a folder
Step 5:
Your server gets file details
req.file
Basic setup
1. Install Multer
npm install multer
2. Set storage (where files will go)
import multer from "multer";
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "uploads/");
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname);
},
});
Meaning:
files will be saved in
uploads/foldereach file will have a unique name
3. Create upload middleware
const upload = multer({ storage });
Single file upload
app.post("/upload", upload.single("photo"), (req, res) => {
console.log(req.file);
res.send("File uploaded successfully");
});
Meaning:
only one file is uploaded
file data is in
req.file
Multiple file upload
app.post("/upload", upload.array("photos", 5), (req, res) => {
console.log(req.files);
res.send("Multiple files uploaded successfully");
});
Meaning:
multiple files allowed
maximum 5 files
file data is in
req.files
Show uploaded files in browser
app.use("/uploads", express.static("uploads"));
Now files can be opened like:
http://localhost:3000/uploads/image.jpg
Full flow
User selects file
β
Browser sends file
β
Server receives request
β
Multer handles file
β
File is saved in uploads folder
β
Server gets file info (req.file)
β
Response is sent