Express File Upload Middleware

1.5.2 · active · verified Wed Apr 22

express-fileupload is a straightforward middleware for the Express.js framework, designed to simplify handling multipart/form-data for file uploads. It acts as a wrapper around the `Busboy` parser, exposing uploaded files via `req.files` for easy access. The current stable version is 1.5.2, with minor releases and bug fixes occurring relatively frequently to address issues and introduce small features like custom loggers or hash algorithm options. Key differentiators include its simple API that provides a `mv()` function for relocating uploaded files, direct access to file properties (name, mimetype, size, data buffer), and an option to utilize temporary files on disk instead of memory, which is beneficial for handling large uploads efficiently. The middleware is actively maintained and offers robust handling of file streams.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic Express server configured with `express-fileupload` to handle file uploads. It shows how to initialize the middleware with options like temporary file usage and size limits, how to access uploaded files via `req.files`, and how to move them to a permanent location using the `mv()` method. A simple HTML form is also provided for testing the upload functionality.

import express from 'express';
import fileUpload from 'express-fileupload';
import path from 'path';
import { promises as fs } from 'fs';

const app = express();
const PORT = process.env.PORT || 3000;
const UPLOAD_DIR = path.join(process.cwd(), 'uploads');

// Create upload directory if it doesn't exist
fs.mkdir(UPLOAD_DIR, { recursive: true }).catch(console.error);

// Middleware: Enable file uploads with temporary files
app.use(fileUpload({
  useTempFiles: true,
  tempFileDir: '/tmp/', // Ensure this directory exists and is writable
  limits: { fileSize: 50 * 1024 * 1024 } // 50MB limit
}));

app.post('/upload', async (req, res) => {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  // 'foo' is the name of the input field in the form
  const uploadedFile = req.files.foo;

  // Check if uploadedFile is an array (multiple files with same name attribute)
  // For simplicity, assume single file upload with 'foo' name.
  if (Array.isArray(uploadedFile)) {
    return res.status(400).send('Multiple files for a single input field not supported in this example.');
  }

  const uploadPath = path.join(UPLOAD_DIR, uploadedFile.name);

  try {
    await uploadedFile.mv(uploadPath);
    res.send(`File uploaded to ${uploadPath}`);
  } catch (err) {
    console.error(err);
    res.status(500).send(err.message);
  }
});

app.get('/', (req, res) => {
  res.send(`
    <h1>Upload a File</h1>
    <form action="/upload" method="post" enctype="multipart/form-data">
      <input type="file" name="foo" />
      <input type="submit" value="Upload" />
    </form>
  `);
});

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
  console.log(`Uploads will be saved to ${UPLOAD_DIR}`);
});

view raw JSON →