DEV Community

Cover image for How to Handle File Uploads in Node.js Using Multer
Syed Mudasser Anayat
Syed Mudasser Anayat

Posted on

How to Handle File Uploads in Node.js Using Multer

Introduction

Handling file uploads is a common requirement in many web applications. In Node.js, one of the most popular libraries to manage file uploads is Multer. It is middleware for handling multipart/form-data, which is used for uploading files.


Why Use Multer?

Multer makes it easy to handle file uploads by parsing incoming request bodies and storing uploaded files directly to disk or memory. It integrates seamlessly with Express and is easy to configure.


Setting Up the Project

Step 1: Initialize Node.js Project

mkdir file-upload-app
cd file-upload-app
npm init -y
Enter fullscreen mode Exit fullscreen mode

Step 2: Install Required Packages

npm install express multer
Enter fullscreen mode Exit fullscreen mode

Basic File Upload Example

Create index.js

const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;

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

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

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

app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Create Upload Directory

mkdir uploads
Enter fullscreen mode Exit fullscreen mode

Testing the Upload

Use tools like Postman or a simple HTML form to test the upload:

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="myfile" />
  <button type="submit">Upload</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Conclusion

Multer is a powerful and flexible middleware for handling file uploads in Node.js. With just a few lines of code, you can set up a robust upload system for your web application. For advanced use-cases, Multer also supports file filtering, size limits, and memory storage.

Let me know if you'd like to see an example with multiple file uploads or uploading to cloud storage like Cloudinary!

Top comments (2)

Collapse
 
taogeegi profile image
taogeegi

Great sharing, I recommend using @servbay to build an environment, which is faster!

Collapse
 
syed_mudasseranayat_e251 profile image
Syed Mudasser Anayat

Thank you so much for recomendation