subir-multiples-ficheros-multer

What is Multer and How to Use It to Upload Files in Express

  • 3 min

Multer is a Node.js middleware designed to handle file uploads in web applications, typically in combination with Express.

Its main function is to facilitate uploading files through web forms, which is essential for any application that needs to handle files, such as images, documents, or videos.

With Multer, we can easily manage file uploads and perform operations on them, such as storage on disk or in memory.

It provides several useful features for working with files:

  • Storage: Allows specifying whether files should be stored on disk or in memory.
  • File filtering: Allows validating and filtering files based on their type, size, and other properties.
  • Custom routes: Facilitates configuring routes to store files and handle them according to our needs.

How to Install Multer

To start using Multer, we first need to install it in our Node.js project. We assume you already have an Express project set up. If not, we can start one with:

npm init -y npm install express

Then, install Multer via npm:

npm install multer

How to Use Multer

To use Multer, we need to configure it and add it as middleware in our Express routes. Let’s see how to do it with a simple example that handles uploading a single file.

Create a Multer Instance

First, import Multer and configure the storage. In this example, we store files on disk:

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

// Storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    // Define the destination directory
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    // Define the file name
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

// Create an instance of Multer with the storage configuration
const upload = multer({ storage: storage });
Copied!

Configure a Route

Now, we configure a route in our Express server that will handle file uploads. We use the upload.single middleware to process a single file in the file field.

const express = require('express');
const app = express();

// Route to upload a single file
app.post('/upload', upload.single('file'), (req, res) => {
  // The uploaded file will be available in req.file
  console.log(req.file);
  res.send('File uploaded successfully.');
});

// Start the server
app.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});
Copied!

In this case, upload.single('file') indicates that the form field containing the file is named file. The information about the uploaded file will be available in req.file.

Handling Multiple Files

If we need to upload multiple files at once, we can use upload.array or upload.fields. Below, we show how to use upload.array to upload several files in a single field:

app.post('/uploads', upload.array('files', 10), (req, res) => {
  // The uploaded files will be available in req.files
  console.log(req.files);
  res.send('Files uploaded successfully.');
});
Copied!

In this example, upload.array('files', 10) indicates that the form field is named files and allows uploading up to 10 files.

File Filtering

Multer also allows filtering files based on their type or size. We can use the fileFilter option to specify filtering conditions:

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    // Accept only image files
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Only image files are allowed.'), false);
    }
  }
});
Copied!

Error Handling

It’s important to handle errors that may arise during file uploads. We can do this by adding an error handling middleware to our Express application:

app.use((err, req, res, next) => {
  if (err) {
    res.status(400).send(`Error: ${err.message}`);
  } else {
    next();
  }
});
Copied!