Skip to main content

Command Palette

Search for a command to run...

Handling File Uploads in Express with Multer

Updated
β€’3 min read

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/ folder

  • each 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