File Upload Functionality with Multer in Node.js

 File Upload Functionality with Multer in Node.js

Handling file uploads is a common requirement in web applications. In Node.js, Multer is the most popular middleware for uploading files with Express. It simplifies parsing multipart/form-data — the encoding type used for file uploads — and provides easy configuration for storage and file handling.

Here’s how you can set up file uploads in a Node.js app using Multer:


1. Install Multer

First, install Multer in your project directory:

npm install multer


2. Require and configure Multer

In your Express app, import Multer and set up a storage engine to control where and how files are saved:

const multer = require('multer');

// Define storage options

const storage = multer.diskStorage({

  destination: function (req, file, cb) {

    cb(null, 'uploads/'); // 'uploads' folder to store files

  },

  filename: function (req, file, cb) {

    cb(null, Date.now() + '-' + file.originalname); // Unique file name

  }

});

// Initialize upload middleware

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


3. Create an upload route

Define an Express route to handle file uploads. Here’s an example for uploading a single file named profileImage:

const express = require('express');

const app = express();

app.post('/upload', upload.single('profileImage'), (req, res) => {

  try {

    console.log('File uploaded:', req.file);

    res.send('File uploaded successfully!');

  } catch (err) {

    res.status(500).send('Error uploading file.');

  }

});


4. Handling multiple files

To upload multiple files, you can use:

app.post('/upload-multiple', upload.array('photos', 5), (req, res) => {

  console.log('Files uploaded:', req.files);

  res.send('Multiple files uploaded successfully!');

});


5. Security tips

  • Validate file types (e.g., only allow images) by adding a fileFilter function in the Multer config.
  • Limit file sizes using the limits option.
  • Always sanitize file names or store them with unique IDs to prevent overwriting.


6. Final step

Create an uploads/ directory in your project root (or configure a different path), and make sure your server has write permissions to it.


Conclusion

With just a few lines of code, Multer makes file uploads in Node.js simple and reliable. Whether you’re building user profile uploads or handling documents, Multer is the go-to choice for Express applications.

Learn MERN Stack Training Course

Read More:

React Router DOM: Simplifying Navigation

Using Axios to Handle API Requests in React

How to Build a Real-Time Chat App Using MERN and Socket.io

Building Single Page Applications (SPA) with Blazor

Visit Quality Thought Training Institute

Get Direction

Comments

Popular posts from this blog

Regression Analysis in Python

Advanced Color Correction Techniques

How to Backup and Store Video Projects Safely