How to use Multer to upload files in Node.js and Express

·

5 min read

If you are developing a web application with Node.js and Express, you might want to use Multer to handle file uploads. Multer is a middleware that can process multipart/form-data forms, which are commonly used for uploading files. In this article, you will learn how to use Multer and what each part of the code does.

What is Multer?

Multer is a Node.js module that works as a middleware for Express and similar frameworks. A middleware is a function that runs between the request and the response, and can modify them in some way. Multer modifies the request by parsing the form data and attaching the files and the text fields to the request object.

Multer is written on top of busboy, which is a module that can handle incoming HTML form data in requests. Multer makes it easier to work with file uploads by providing various options and features, such as:

  • Storage engines: You can choose where to store the uploaded files, either on disk or in memory.

  • File filters: You can filter out unwanted files based on criteria such as file size, file type, or file name.

  • Error handling: You can handle errors that may occur during file uploads, such as invalid form data, missing fields, or storage errors.

  • Metadata: You can access metadata of the uploaded files, such as file name, file size, file type, and file path.

How to use Multer?

To use Multer, you need to install it with npm:

npm install --save multer

Then, you need to import it in your Node.js file and create a multer instance with some options:

// This imports the multer module
const multer = require('multer');

// This creates a multer instance with some options
const upload = multer({ /* options */ });

The options object can contain various properties that configure how Multer should handle the file uploads. One of the most important properties is storage, which defines where and how to store the uploaded files. Multer provides two built-in storage engines: diskStorage and memoryStorage.

The diskStorage engine allows you to store the uploaded files on disk, in a specified directory. You can also customize the file names using a filename function. The memoryStorage engine allows you to store the uploaded files in memory, as Buffer objects. This can be useful if you want to process the files without saving them.

Here is an example of how to use the diskStorage engine:

/* FILE STORAGE */

// This defines a storage engine for storing files on disk
const storage = multer.diskStorage({
    // This defines the destination directory for storing files
    destination: function (req, file, cb) {
        // The cb function is a callback that takes two parameters: an error and a path
        // The null argument means there is no error
        // The "public/assets" argument means the files will be stored in this directory
        cb(null, "public/assets");
    },
    // This defines the file name for storing files
    filename: function (req, file, cb) {
        // The cb function is a callback that takes two parameters: an error and a name
        // The null argument means there is no error
        // The file.originalname argument means the files will be stored with their original names
        cb(null, file.originalname);
    },
});

// This creates a multer instance with the storage engine
const upload = multer({ storage });

The code above defines a storage engine for storing files on disk, in the "public/assets" directory, with their original names. It then creates a multer instance with this storage engine.

To use this multer instance in your Express app, you need to use it as a middleware for your routes that handle file uploads. Multer provides various methods for handling different types of form data:

  • single(fieldname): This method accepts a single file with the name fieldname. The single file will be stored in req.file.

  • array(fieldname[, maxCount]): This method accepts an array of files with the name fieldname. The optional maxCount parameter specifies the maximum number of files allowed. The array of files will be stored in req.files.

  • fields(fields): This method accepts a mix of files specified by fields. The fields parameter is an array of objects with name and maxCount properties. Each object specifies a field name and an optional maximum number of files allowed for that field. The mix of files will be stored in req.files.

  • none(): This method accepts only text fields and no files. The text fields will be stored in req.body.

  • any(): This method accepts any files and text fields. The files will be stored in req.files and the text fields will be stored in req.body.

Here is an example of how to use the single method:

// This uses the multer instance as a middleware for the /upload route
// This route accepts a single file with the name "image"
app.post('/upload', upload.single('image'), function (req, res, next) {
  // req.file is the `image` file
  // req.body will hold the text fields, if there were any
  // You can do something with the file and the body here
});

The code above uses the multer instance as a middleware for the /upload route. This route accepts a single file with the name "image". The file will be stored in req.file and the text fields, if any, will be stored in req.body. You can then do something with the file and the body in your route handler.

Conclusion

Multer is a useful module that helps you handle file uploads in Node.js and Express by parsing multipart/form-data forms and attaching the files and the text fields to the request object. You can use Multer as a middleware for your routes that handle file uploads and configure various options and features, such as storage engines, file filters, error handling, and metadata. Multer is not a silver bullet, but it can make your file upload process much easier and more efficient.