What is Multer? How To Handling File Uploads in Node.js

By Saheb Sutradhar - Updated On 13-03-2024

What is Multer? How To Handling File Uploads in Node.js



Multer is a Node.js middleware designed to handle multipart/form-data in forms. If you’ve ever dealt with file uploads in Node.js, you know it can be a bit of a headache. That’s where Multer comes to the rescue! In this article, we’ll explore what Multer is, how it works, and how to use it effectively.

What is Multer?

Multer is like the trusty sidekick for handling file uploads in your Node.js applications. It’s similar to the popular body-parser middleware that’s built into Express for handling form submissions. However, Multer shines when it comes to processing multipart data, specifically multipart/form-data forms.

Here are the key points about Multer:

  • Handles multipart/form-data: Multer is specifically designed to process form data that includes files. It’s perfect for scenarios where you need users to upload images, documents, or any other type of file.
  • Efficient and lightweight: Multer is built on top of busboy, which ensures maximum efficiency while handling file uploads.
  • Easy integration: You can seamlessly integrate Multer into your Express application without much hassle.

How to Use Multer In Node JS

Let’s dive into some practical examples of how to use Multer:

1. Getting Started with Multer

Before diving into the code, you'll need to set up a Node.js project. If you haven't already, initialize a new Node.js project by running npm init in your terminal and follow the prompts. Once your project is set up, you can install Multer using npm:

npm install multer

2. Using Multer in Your Node.js Application

Let's create a simple Node.js application to demonstrate how to use Multer for file uploads. First, create a new JavaScript file, e.g., app.js, and require the necessary modules:

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

Next, initialize an Express application and configure Multer:

const app = express();

// Set storage engine
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/'); // Specify the destination directory
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); // Specify the file name
  }
});

// Initialize multer middleware
const upload = multer({ storage: storage });

In the above code, we've configured Multer to store uploaded files in the uploads/ directory. We've also specified a naming convention for the uploaded files.

Now, let's define a route to handle file uploads:

// Define a single file upload route
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully');
});

In this route, we've specified that we expect a single file with the field name file. When a file is uploaded, Multer saves it to the specified destination directory.

Finally, start the server and listen on a port:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

3. HTML File Uploads

To test the file upload functionality, you can create a simple HTML form:

<form action="/upload" method="POST" enctype="multipart/form-data">
  <input type="file" name="file">
  <button type="submit">Upload</button>
</form>

When you submit this form with a file selected, it will be uploaded to the server, and you'll receive a "File uploaded successfully" message.

Complete Code Example

app.js

// app.js

// Required modules
const express = require('express');
const multer = require('multer');
const path = require('path');

// Initialize Express app
const app = express();

// Set storage engine
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null, 'uploads/'); // Specify the destination directory
  },
  filename: function(req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)); // Specify the file name
  }
});

// Initialize multer middleware
const upload = multer({ storage: storage });

// Define a single file upload route
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded successfully');
});

// Serve the HTML form
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

index.html

<!-- index.html -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Upload</title>
</head>
<body>
  <h2>Upload a File</h2>
  <form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Upload</button>
  </form>
</body>
</html>

To run this Code, you should have Node.js installed on your machine. Then, follow these steps:

  1. Create a project directory and navigate to it.
  2. Create the app.js file and copy the code provided above into it.
  3. Create an uploads directory in the project root (where app.js is located).
  4. Create the index.html file and copy the HTML code provided above into it.
  5. Open your terminal, navigate to the project directory, and run npm init to initialize a new Node.js project. Follow the prompts to create a package.json file.
  6. Install the required dependencies by running npm install express multer.
  7. Start the server by running node app.js.
  8. Open your web browser and navigate to http://localhost:3000 to access the file upload form.
  9. Select a file using the input field and click the "Upload" button to upload it to the server.

You should see a message saying "File uploaded successfully" after the file has been uploaded. The uploaded files will be stored in the uploads directory.

codelearningpoint © 2024