Multer File Upload: Complete Setup Guide (Express.js)

Handling file uploads in Node.js can feel tricky, especially when dealing with multipart/form-data. This is where Multer comes in — a simple and efficient middleware designed specifically for handling file uploads in Express applications.

What is Multer in Node.js?

Multer is a middleware for Node.js that helps you handle multipart/form-data, which is primarily used for uploading files.

It works seamlessly with Express and processes incoming form data by:

How to use Multer with Express?

To use Multer, you need to:

  1. Install it
  2. Configure storage
  3. Attach it as middleware in your route

How do I install Multer using npm?

npm install multer
npm install express

How does Multer handle multipart/form-data?

When a form is submitted with enctype="multipart/form-data", Multer:

Basic example of uploading a file using Multer

Step 1: Setup Express and Multer

const express = require("express");
const multer = require("multer");

const app = express();

Step 2: Configure storage

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({ storage: storage });

Step 3: Create upload route

app.post("/upload", upload.single("file"), (req, res) => {
  res.send("File uploaded successfully");
});

Step 4: Start server

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

Step 5: HTML form example

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file" />
  <button type="submit">Upload</button>
</form>

How to handle form data and file uploads together?

Multer can process both files and text inputs in the same request.

Example:

app.post("/submit", upload.single("file"), (req, res) => {
  const file = req.file;
  const name = req.body.name;
  const email = req.body.email;

  res.json({
    message: "Form submitted successfully",
    file,
    name,
    email,
  });
});

HTML form:

<form action="/submit" method="POST" enctype="multipart/form-data">
  <input type="text" name="name" placeholder="Enter name" />
  <input type="email" name="email" placeholder="Enter email" />
  <input type="file" name="file" />
  <button type="submit">Submit</button>
</form>

Key Takeaways