File Upload with Multer

Node js 10 min min read Updated: Mar 30, 2026 Intermediate
File Upload with Multer
Intermediate Topic 9 of 10

File Upload with Multer in Node.js

Uploading files is one of the most common requirements in web applications. For example, users may need to upload profile pictures, documents, certificates, videos, or attachments. In a Node.js application, handling file uploads becomes much easier with the help of Multer.

Multer is a middleware for Express.js that is specially built for handling multipart/form-data. This content type is mainly used when a form includes file uploads. In this tutorial, Node.js students will learn what Multer is, why it is needed, how it works, and how to use it with practical code examples.

Why File Upload Handling is Different

When we submit normal form data such as name, email, or password, Express can handle it easily using middleware like express.json() or express.urlencoded(). But when a form includes a file, the request format changes to multipart/form-data.

This format contains binary file data along with regular text fields. Express does not process this format automatically, so we need a special middleware. That is where Multer comes in. It reads the uploaded file, stores it, and makes the file details available inside the request object.

What is Multer?

Multer is a Node.js middleware used for handling file uploads in Express applications. It processes multipart/form-data requests and helps developers save uploaded files either in memory or on disk.

Multer is popular because it is simple to configure, works smoothly with Express, and gives control over file names, storage location, file size limits, and file type validation.

Benefits of Multer

Some major benefits of Multer are listed below:

  • It makes file uploading easy in Express applications.
  • It supports single, multiple, and mixed file uploads.
  • It allows custom file naming.
  • It supports file validation and size restrictions.
  • It is useful for real-world projects like profile uploads, resumes, document systems, and media platforms.

Installing Multer

To start using Multer, first install Express and Multer in your project.

bashnpm install express multer

Once the packages are installed, you are ready to create a file upload server.

Basic Express Server Setup

Before writing the upload logic, let us create a simple Express server.

javascriptconst express = require("express"); const app = express(); app.listen(3000, () => { console.log("Server running on port 3000"); });

This code creates a basic Node.js server using Express and starts it on port 3000.

Creating an Uploads Folder

In most beginner projects, uploaded files are stored inside a local folder. For that, create an uploads folder in your project root. Multer will save uploaded files there.

A simple project structure may look like this:

bashproject-folder/ │ ├── uploads/ ├── app.js └── package.json

Configuring Multer Storage

Multer allows us to define where the file should be stored and what its final name should be. The most common storage option for students is diskStorage.

javascriptconst multer = require("multer"); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "uploads/"); }, filename: function (req, file, cb) { const uniqueName = Date.now() + "-" + file.originalname; cb(null, uniqueName); } }); const upload = multer({ storage: storage });

In this configuration, the destination function defines the folder where files will be stored. The filename function sets a unique file name by adding the current timestamp before the original file name. This prevents duplicate file name conflicts.

Understanding the Storage Configuration

Let us understand the important parts of the Multer storage setup:

  • destination: decides the folder path where uploaded files will be stored.
  • filename: decides the final file name that will be saved on the server.
  • cb: is the callback function used by Multer to return the storage result.

This setup is very useful because in real projects many users may upload files with the same name like photo.png or resume.pdf. Adding a timestamp helps avoid overwriting existing files.

Uploading a Single File

Now let us upload a single file using Multer. Suppose the file input field name is profile.

javascriptapp.post("/upload", upload.single("profile"), (req, res) => { console.log(req.file); res.json({ message: "File uploaded successfully", file: req.file }); });

Here, upload.single("profile") tells Multer to accept only one file from the field named profile. After upload, the file details become available in req.file.

How Single File Upload Works

When the client sends a file from the form field profile, Multer reads the request, saves the file to the uploads folder, and adds an object into req.file. This object contains useful information such as file name, size, type, and path.

This is commonly used when a user uploads a single item like a profile picture, CV, PAN card, Aadhaar document, or product image.

Example HTML Form for Single Upload

To test the API from a browser, you can use an HTML form like this:

html<form action="http://localhost:3000/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="profile" /> <button type="submit">Upload File</button> </form>

The most important part here is enctype="multipart/form-data". Without it, the browser will not send the file correctly.

Uploading Multiple Files

Sometimes a user needs to upload multiple images or documents together. Multer supports this through the array() method.

javascriptapp.post("/multiple-upload", upload.array("photos", 5), (req, res) => { console.log(req.files); res.json({ message: "Multiple files uploaded successfully", files: req.files }); });

In this example, upload.array("photos", 5) means the server will accept up to 5 files from the field named photos. All uploaded files will be available in req.files.

Where Multiple Upload is Used

Multiple file upload is useful in many situations such as:

  • Uploading multiple product images in an e-commerce app
  • Uploading photo galleries
  • Submitting assignment files
  • Uploading multiple certificates or documents

Uploading Files from Multiple Fields

In some forms, different file input fields are used for different purposes. For example, one field may upload a profile image and another may upload documents. Multer supports this using fields().

javascriptapp.post("/upload-fields", upload.fields([ { name: "profile", maxCount: 1 }, { name: "documents", maxCount: 3 } ]), (req, res) => { console.log(req.files); res.json({ message: "Files uploaded successfully", files: req.files }); });

This method is helpful when a form contains multiple named file inputs.

Limiting File Size

In practical applications, it is risky to allow unlimited file uploads because very large files can slow down the server or consume too much storage. Multer allows file size restrictions using the limits property.

javascriptconst upload = multer({ storage: storage, limits: { fileSize: 2 * 1024 * 1024 } });

This example sets the maximum file size to 2 MB. If a user tries to upload a file larger than this limit, Multer will throw an error.

Why File Size Limit is Important

File size limits improve server performance and security. Without limits, users may upload unnecessarily large files that can fill storage quickly or affect application speed. For student-level projects, setting a clear limit is always a good practice.

Filtering File Types

Often, we do not want users to upload every kind of file. For example, a profile image upload should accept only image files like JPG and PNG. Multer provides a fileFilter option for this purpose.

javascriptconst upload = multer({ storage: storage, fileFilter: function (req, file, cb) { const allowedTypes = ["image/jpeg", "image/png"]; if (allowedTypes.includes(file.mimetype)) { cb(null, true); } else { cb(new Error("Only JPG and PNG files are allowed")); } } });

This filter checks the MIME type of the uploaded file. If the file type is not allowed, Multer returns an error.

Why File Validation is Necessary

File validation is very important because users may accidentally or intentionally upload the wrong file type. For example, if your application expects an image but someone uploads an executable file, that can create security risks. Validating the file type ensures better control and safer uploads.

Accessing Uploaded File Information

After a successful upload, Multer provides file information in the request object. For single file uploads, you can access it through req.file.

javascriptconsole.log(req.file);

A typical output may look like this:

javascript{ fieldname: "profile", originalname: "photo.png", encoding: "7bit", mimetype: "image/png", destination: "uploads/", filename: "17100012345-photo.png", path: "uploads/17100012345-photo.png", size: 125000 }

This information is very useful when saving file details into a database. For example, you can store the file name, path, and size in a users table or documents table.

Complete Practical Example

Now let us combine everything into one practical Node.js application for single image upload.

javascriptconst express = require("express"); const multer = require("multer"); const app = express(); const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "uploads/"); }, filename: function (req, file, cb) { const uniqueName = Date.now() + "-" + file.originalname; cb(null, uniqueName); } }); const upload = multer({ storage: storage, limits: { fileSize: 2 * 1024 * 1024 }, fileFilter: function (req, file, cb) { const allowedTypes = ["image/jpeg", "image/png"]; if (allowedTypes.includes(file.mimetype)) { cb(null, true); } else { cb(new Error("Only JPG and PNG files are allowed")); } } }); app.post("/upload", upload.single("profile"), (req, res) => { res.json({ message: "File uploaded successfully", file: req.file }); }); app.listen(3000, () => { console.log("Server is running on port 3000"); });

This example is simple, practical, and suitable for Node.js students who want to understand the real use of Multer in a backend application.

Error Handling in Multer

When working with file uploads, errors may happen. A file may be too large, the file type may be invalid, or the upload field may be missing. Good applications should handle such errors properly.

javascriptapp.post("/upload", (req, res) => { upload.single("profile")(req, res, function (err) { if (err) { return res.status(400).json({ error: err.message }); } if (!req.file) { return res.status(400).json({ error: "No file uploaded" }); } res.json({ message: "File uploaded successfully", file: req.file }); }); });

This approach gives more control because we can return proper error messages to the client.

Best Practices for Students

While learning file uploads, students should follow some best practices:

  • Always validate file type before accepting uploads.
  • Always set a file size limit.
  • Use unique file names to avoid overwriting.
  • Store only necessary file information in the database.
  • Do not trust file extensions alone; check MIME type too.
  • For large projects, prefer cloud storage like AWS S3 instead of local folders.

Real-World Use Cases of Multer

Multer is used in many real applications. Some common examples are:

  • User profile image upload
  • Resume upload in job portals
  • Product image upload in e-commerce applications
  • Document submission systems
  • Media upload panels for admin dashboards

So learning Multer is not just useful for practice, but also very helpful for building production-ready Node.js projects.

Conclusion

File upload is an essential feature in modern web development, and Multer makes this task much easier in Node.js and Express applications. In this tutorial, students learned what Multer is, why it is required, how to configure storage, how to upload single and multiple files, how to validate file type and file size, and how to build a complete working example.

For beginners, Multer is one of the best middleware packages to learn because it is simple, practical, and used widely in real-world backend systems. Once students understand the basics of Multer, they can move to advanced topics such as cloud uploads, database integration, image resizing, and secure file management.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators