Multer

2.1.1 · active · verified Sat Apr 18

Multer is a Node.js middleware designed for efficiently handling `multipart/form-data`, primarily used for uploading files. It builds on the busboy library for maximum performance and integrates seamlessly with Express. The current stable version is 2.1.1, with recent releases frequently addressing critical security vulnerabilities (CVEs), indicating active and diligent maintenance.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up an Express route with Multer to handle a single file upload from a `multipart/form-data` form. It saves the file to a local 'uploads/' directory and makes the file and text fields accessible via `req.file` and `req.body` respectively.

const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// Ensure the 'uploads' directory exists
const uploadDir = 'uploads';
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// Configure Multer storage
const upload = multer({ dest: uploadDir });

const app = express();

// Route to handle single file upload
app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  if (req.file) {
    console.log(`File uploaded: ${req.file.originalname} (${req.file.mimetype})`);
    console.log(`Saved to: ${req.file.path}`);
  } else {
    console.log('No file uploaded.');
  }
  if (Object.keys(req.body).length > 0) {
    console.log('Form data:', req.body);
  }
  res.send('File upload processed!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));

view raw JSON →