Close Menu
Arunangshu Das Blog
  • SaaS Tools
    • Business Operations SaaS
    • Marketing & Sales SaaS
    • Collaboration & Productivity SaaS
    • Financial & Accounting SaaS
  • Web Hosting
    • Types of Hosting
    • Domain & DNS Management
    • Server Management Tools
    • Website Security & Backup Services
  • Cybersecurity
    • Network Security
    • Endpoint Security
    • Application Security
    • Cloud Security
  • IoT
    • Smart Home & Consumer IoT
    • Industrial IoT
    • Healthcare IoT
    • Agricultural IoT
  • Software Development
    • Frontend Development
    • Backend Development
    • DevOps
    • Adaptive Software Development
    • Expert Interviews
      • Software Developer Interview Questions
      • Devops Interview Questions
    • Industry Insights
      • Case Studies
      • Trends and News
      • Future Technology
  • AI
    • Machine Learning
    • Deep Learning
    • NLP
    • LLM
    • AI Interview Questions
  • Startup

Subscribe to Updates

Subscribe to our newsletter for updates, insights, tips, and exclusive content!

What's Hot

Building Responsible AI: Addressing AI Ethics and Bias in Development

June 9, 2025

Serverless Computing vs. Traditional Cloud Hosting: A Deep Dive into the Future of Tech Infrastructure

February 26, 2025

How does a Content Delivery Network (CDN) improve performance?

November 8, 2024
X (Twitter) Instagram LinkedIn
Arunangshu Das Blog Saturday, July 5
  • Write For Us
  • Blog
  • Gallery
  • Contact Me
  • Newsletter
Facebook X (Twitter) Instagram LinkedIn RSS
Subscribe
  • SaaS Tools
    • Business Operations SaaS
    • Marketing & Sales SaaS
    • Collaboration & Productivity SaaS
    • Financial & Accounting SaaS
  • Web Hosting
    • Types of Hosting
    • Domain & DNS Management
    • Server Management Tools
    • Website Security & Backup Services
  • Cybersecurity
    • Network Security
    • Endpoint Security
    • Application Security
    • Cloud Security
  • IoT
    • Smart Home & Consumer IoT
    • Industrial IoT
    • Healthcare IoT
    • Agricultural IoT
  • Software Development
    • Frontend Development
    • Backend Development
    • DevOps
    • Adaptive Software Development
    • Expert Interviews
      • Software Developer Interview Questions
      • Devops Interview Questions
    • Industry Insights
      • Case Studies
      • Trends and News
      • Future Technology
  • AI
    • Machine Learning
    • Deep Learning
    • NLP
    • LLM
    • AI Interview Questions
  • Startup
Arunangshu Das Blog
  • Write For Us
  • Blog
  • Gallery
  • Contact Me
  • Newsletter
Home»Software Development»Backend Development»Handling File Uploads in Node.js with Multer
Backend Development

Handling File Uploads in Node.js with Multer

Arunangshu DasBy Arunangshu DasJuly 23, 2024Updated:February 26, 2025No Comments4 Mins Read
Facebook Twitter Pinterest Telegram LinkedIn Tumblr Copy Link Email Reddit Threads WhatsApp
Follow Us
Facebook X (Twitter) LinkedIn Instagram
Share
Facebook Twitter LinkedIn Pinterest Email Copy Link Reddit WhatsApp Threads

Uploading files is a common requirement in many web applications. Whether you’re building a profile picture uploader, a document management system, or a cloud storage service, you’ll need to handle file uploads efficiently and securely. In Node.js, one of the most popular libraries for handling file uploads is Multer.

What is Multer?

Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy library and makes it easy to handle file uploads in Node.js applications.

Setting Up Multer

Before we start, make sure you have Node.js and npm (Node Package Manager) installed on your machine. If not, you can download and install them from Node.js official website.

  1. Initialize Your ProjectFirst, create a new directory for your project and initialize a new Node.js project.
mkdir file-upload-example
cd file-upload-example
npm init -y

2. Install Dependencies

Next, install the necessary dependencies. We’ll need Express for our web server and Multer for handling file uploads.

npm install express multer

Create the Server

Create a new file named server.js and set up a basic Express server.

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

const app = express();

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

// Initialize upload
const upload = multer({
  storage: storage,
  limits: { fileSize: 1000000 }, // Limit file size to 1MB
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  }
}).single('myImage');

// Check File Type
function checkFileType(file, cb) {
  // Allowed ext
  const filetypes = /jpeg|jpg|png|gif/;
  // Check ext
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  // Check mime
  const mimetype = filetypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images Only!');
  }
}

app.get('/', (req, res) => res.send('Hello World!'));

app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      res.send(err);
    } else {
      if (req.file == undefined) {
        res.send('Error: No File Selected!');
      } else {
        res.send(`File Uploaded: ${req.file.filename}`);
      }
    }
  });
});

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));

Understanding Multer Configuration

  1. Storage EngineThe storage engine determines how and where the files will be stored. In the above example, we’re using the diskStorage engine, which saves the files to the disk. We specify the destination directory and filename.
const storage = multer.diskStorage({
  destination: './uploads/',
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  }
});

File Size Limit

You can set a file size limit to prevent users from uploading excessively large files.

limits: { fileSize: 1000000 } // Limit file size to 1MB

File Filter

The file filter allows you to control which files are accepted. In the example, we only accept image files (JPEG, JPG, PNG, GIF).

function checkFileType(file, cb) {
  const filetypes = /jpeg|jpg|png|gif/;
  const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
  const mimetype = filetypes.test(file.mimetype);

  if (mimetype && extname) {
    return cb(null, true);
  } else {
    cb('Error: Images Only!');
  }
}

Handling File Uploads in Routes

In the example, we set up a POST route /upload to handle the file uploads. The upload middleware is called in this route, which processes the file upload.

app.post('/upload', (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      res.send(err);
    } else {
      if (req.file == undefined) {
        res.send('Error: No File Selected!');
      } else {
        res.send(`File Uploaded: ${req.file.filename}`);
      }
    }
  });
});

Security Considerations

When handling file uploads, it’s crucial to consider security to avoid potential vulnerabilities. Here are some tips:

  1. Validate File TypesAlways validate the file type to ensure that only the expected files are uploaded.
  2. Limit File SizeSet appropriate file size limits to prevent denial-of-service (DoS) attacks.
  3. Use Safe FilenamesEnsure that filenames are sanitized to prevent directory traversal attacks. Multer does this by default when generating filenames.
  4. Store Files SecurelyStore uploaded files in a secure directory and consider using unique filenames to avoid overwriting files.

Conclusion

Handling file uploads in Node.js is straightforward with Multer. It provides a simple yet powerful way to manage file uploads, with plenty of configuration options to meet your needs.

Backend Development File File Upload Node js
Follow on Facebook Follow on X (Twitter) Follow on LinkedIn Follow on Instagram
Share. Facebook Twitter Pinterest LinkedIn Telegram Email Copy Link Reddit WhatsApp Threads
Previous ArticleGraphQL vs REST: Which is Better for Frontend Development?
Next Article Database Design Principles for Scalable Applications

Related Posts

Building Robust APIs: Essential REST API Design Principles for Developers

June 15, 2025

Microservices Architecture: What IsIt?

June 5, 2025

7 Common CORS Errors and How to Fix Them

February 26, 2025
Add A Comment
Leave A Reply Cancel Reply

Top Posts

How to Build Resilient Teams with Adaptive Software Development

January 22, 2025

IoT Solutions for Smart Offices and Enterprise Efficiency: Transforming the Modern Workplace

February 26, 2025

Optimizing Real-Time Applications in Node.js with WebSockets and GraphQL

December 23, 2024

Adaptive Software Development vs. Scrum: Key Differences

January 17, 2025
Don't Miss

The Rise of Low-Code and No-Code Platforms

October 5, 20246 Mins Read

In recent years, the software development landscape has been undergoing a significant transformation with the…

5 Benefits of Using Chatbots in Modern Business

February 17, 2025

How to Migrate Legacy Applications to the Cloud Efficiently

February 26, 2025

Key Considerations for Developers Building Software

July 2, 2024
Stay In Touch
  • Facebook
  • Twitter
  • Pinterest
  • Instagram
  • LinkedIn

Subscribe to Updates

Subscribe to our newsletter for updates, insights, and exclusive content every week!

About Us

I am Arunangshu Das, a Software Developer passionate about creating efficient, scalable applications. With expertise in various programming languages and frameworks, I enjoy solving complex problems, optimizing performance, and contributing to innovative projects that drive technological advancement.

Facebook X (Twitter) Instagram LinkedIn RSS
Don't Miss

Ridge Regression

March 31, 2024

5 Key Features of RESTful APIs

February 23, 2025

How does web browser rendering work?

January 1, 2025
Most Popular

Top Benefits of Adopting Adaptive Software Development

January 17, 2025

How to Optimize Website Performance Using Chrome DevTools

December 18, 2024

Named Entity Recognition (NER) in Natural Language Processing (NLP)

May 15, 2024
Arunangshu Das Blog
  • About Me
  • Contact Us
  • Write for Us
  • Advertise With Us
  • Privacy Policy
  • Terms & Conditions
  • Disclaimer
  • Article
  • Blog
  • Newsletter
  • Media House
© 2025 Arunangshu Das. Designed by Arunangshu Das.

Type above and press Enter to search. Press Esc to cancel.

Ad Blocker Enabled!
Ad Blocker Enabled!
Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.