Node.js & Express: How to Upload Files Using Multer

Updated: December 28, 2023 By: Guest Contributor Post a comment

Overview

Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of busboy (busboy – not badboy – a streaming parser for HTML form data for Node.js) for maximum efficiency. This tutorial will demonstrate how to use Multer in an Express.js application for file uploads, step-by-step, enhancing your understanding from basic to more advanced implementations.

Setting up the Project

First, you’ll need to create a new Express.js application. If you don’t have Express installed, you can install it globally using the following NPM command:

npm install -g express-generator
express my-upload-app
cd my-upload-app
npm install

Now, install Multer:

npm install multer --save

Basic File Upload

Let’s start with a basic file upload. First, set up a simple HTML form that allows file uploading:

<!-- upload.html -->
<form ref='enctype'='multipart/form-data' action='/upload' method='post'>
  <input type='file' name='file'>
  <button type='submit'>Upload File</button>
</form>

In your Express server file, set up a POST route to handle the uploaded file:

// server.js
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

const app = express();

app.post('/upload', upload.single('file'), function (req, res) {
  console.log(req.file);
  res.send('File uploaded successfully.');
});

app.listen(3000, function () {
  console.log('Server started on port 3000');
});

When you go to http://localhost:3000/upload.html and submit the form, your file will be uploaded to the ‘uploads’ directory.

Advanced Usage

For a more advanced scenario, let’s customize the storage engine:

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
});

const upload = multer({ storage: storage });

This configuration allows you to set a custom directory and rename files to prevent overwriting. Multer also supports file filter functionality to control which files should be uploaded:

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  } else {
    cb(new Error('Unsupported file type'), false);
  }
};

const upload = multer({ storage: storage, fileFilter: fileFilter });

Now your server will only accept JPEG or PNG files.

To handle multiple files at once, you can use the upload.array() method or upload.fields() for mixed file types:

app.post('/uploadmultiple', upload.array('files', 3), (req, res) => {
  console.log(req.files);
  res.send('Multiple files uploaded.');
});

// For mixed file types
app.post('/uploadmixed', upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]), (req, res) => {
  console.log(req.files);
  res.send('Mixed files uploaded.');
});

Error Handling

Error handling is crucial for a robust application. With Multer, you can handle different types of errors that occur during the file upload process. You can catch Multer errors or other errors as shown below:

app.post('/upload', upload.single('file'), (req, res) => {
  // Multer will add a 'file' object in 'req' that includes the information about the uploaded file
  // Handle Multer errors
  // Handle other errors
});

Conclusion

Throughout this tutorial, you’ve learned how to implement file uploads in your Node.js and Express application using Multer. Starting from a simple setup to handling more complex scenarios like custom storage paths, file types and handling multiple files, we’ve covered the essential concepts for managing file uploads effectively with Multer.

With the ability to configure and fine-tune how files are handled, Multer is a powerful middleware that adds an important feature set to your web applications. By building upon the basics covered here, you can implement robust and user-friendly file upload solutions.

Now that you’ve gotten your hands dirty with practical examples, the next step is to integrate these techniques into your own projects and continue exploring Multer’s rich feature set. Happy coding!