Language: EN

subir-multiples-ficheros-multer

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

Multer is a Node.js middleware designed to handle file uploads in Express applications.

Its main function is to facilitate the uploading of 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 storing them 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: Enables validation and filtering of files based on their type, size, and other properties.
  • Custom routes: Simplifies the configuration of routes for storing files and handling them according to our needs.

For more information and to explore all the features of Multer, you can visit the official repository on GitHub.

How to Install Multer

To start using Multer, we first need to install it in our Node.js project. We assume that we already have a configured Express project. If we don’t have one yet, we can start one with:

npm init -y
npm install express

Then, we 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 this with a simple example that handles the upload of a file.

Create an Instance of Multer

First, we import Multer and configure the storage. In this example, we store the 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 });

Configure a Route for Uploading

Now, we configure a route on our Express server that will handle file uploads. We use the middleware upload.single 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');
});

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

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

Error Handling

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

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