0
0
ExpressHow-ToBeginner · 4 min read

How to Use Multer in Express for File Uploads

Use multer as middleware in your Express app to handle file uploads by configuring storage and specifying upload fields. Import multer, set storage options, then use upload.single() or upload.array() in your route handlers to process files.
📐

Syntax

Multer is used as middleware in Express routes to handle file uploads. You first import multer, configure storage or use default memory storage, then create an upload handler. Use upload.single('fieldname') for one file or upload.array('fieldname', maxCount) for multiple files.

  • multer(): Initializes multer with options.
  • storage: Defines where and how files are saved.
  • upload.single('fieldname'): Middleware for single file upload.
  • upload.array('fieldname', maxCount): Middleware for multiple files.
javascript
import multer from 'multer';

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 });

app.post('/upload', upload.single('fileField'), (req, res) => {
  res.send('File uploaded');
});
💻

Example

This example shows a simple Express server using multer to upload a single file named avatar. The file is saved in the uploads/ folder with a timestamp prefix to avoid name conflicts. The server responds with a success message after upload.

javascript
import express from 'express';
import multer from 'multer';
import path from 'path';

const app = express();
const PORT = 3000;

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

const upload = multer({ storage });

app.post('/upload-avatar', upload.single('avatar'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded');
  }
  res.send(`File uploaded: ${req.file.filename}`);
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
Output
Server running on http://localhost:3000 // After POST /upload-avatar with form-data including 'avatar' file File uploaded: 1687000000000.jpg
⚠️

Common Pitfalls

  • Not creating the upload folder (uploads/) before running the app causes errors.
  • Using upload.single() but sending multiple files will fail.
  • Forgetting to set enctype="multipart/form-data" in HTML forms prevents file upload.
  • Not handling errors from multer middleware can crash the server.

Always validate file types and sizes for security.

html
/* Wrong: Missing enctype in HTML form */
// <form action="/upload-avatar" method="POST">
//   <input type="file" name="avatar" />
//   <button type="submit">Upload</button>
// </form>

/* Right: Include enctype */
// <form action="/upload-avatar" method="POST" enctype="multipart/form-data">
//   <input type="file" name="avatar" />
//   <button type="submit">Upload</button>
// </form>
📊

Quick Reference

Key points to remember when using multer:

  • Import multer and configure storage.
  • Use upload.single('fieldname') for one file or upload.array('fieldname', maxCount) for multiple files.
  • Ensure your form uses enctype="multipart/form-data".
  • Create the upload directory before running the app.
  • Handle errors and validate files for security.

Key Takeaways

Use multer middleware in Express routes to handle file uploads easily.
Configure storage to control where and how files are saved.
Use upload.single() for single files and upload.array() for multiple files.
Always set form enctype to multipart/form-data for file uploads.
Create upload folders and handle errors to avoid common issues.