NodeJS

Node.js File Upload Application using Express and Multer

📌 INTRODUCTION

File upload is one of the most useful features in web applications. It allows users to upload:

  • Images
  • PDF files
  • Documents
  • Resume files
  • Project reports

In Node.js, file upload is commonly implemented using:

  • Express.js for server creation
  • Multer middleware for handling file uploads

In this program, we will build a simple Node.js File Upload Application that allows users to upload a file and save it in a specified folder.


📘 PROBLEM STATEMENT

👉 Create a Node.js application to upload files and save them to a specified directory.


💡 CONCEPTS USED

  • Node.js
  • Express.js
  • Multer middleware
  • HTML forms
  • File handling
  • Backend routing

🧠 LOGIC EXPLANATION

The application works as follows:

  1. Create an Express server
  2. Use Multer middleware for file upload
  3. Create an uploads folder
  4. Build an HTML form with file input
  5. Submit the file to the server
  6. Save the uploaded file into the folder
  7. Show success message

⚙️ STEP 1: CREATE PROJECT FOLDER

Open terminal and run:

mkdir file-upload-app
cd file-upload-app
npm init -y

⚙️ STEP 2: INSTALL REQUIRED PACKAGES

Install Express and Multer:

npm install express multer

📁 PROJECT STRUCTURE

Your folder structure should look like this:

file-upload-app/

├── uploads/
├── server.js
└── package.json

👉 Create the uploads folder manually inside the project.


💻 PROGRAM CODE

1. Create server.js

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

const app = express();

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

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

// Route to display upload form
app.get("/", (req, res) => {
res.send(`
<h2>File Upload Form</h2>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="myFile" required />
<br><br>
<button type="submit">Upload File</button>
</form>
`);
});

// Route to handle file upload
app.post("/upload", upload.single("myFile"), (req, res) => {
res.send("File uploaded successfully!");
});

// Start server
app.listen(3000, () => {
console.log("Server is running on http://localhost:3000");
});

▶️ HOW TO RUN THE PROGRAM

Run the server using:

node server.js

Now open browser and visit:

http://localhost:3000

🖥️ OUTPUT

On browser:

File Upload Form
[Choose File]
[Upload File]

After selecting a file and clicking upload:

File uploaded successfully!

👉 The uploaded file will be saved inside the uploads folder.


🔍 STEP-BY-STEP EXPLANATION

1. Import Required Modules

const express = require("express");
const multer = require("multer");
const path = require("path");
  • express → used to create server
  • multer → used for uploading files
  • path → used to manage file extensions

2. Configure Storage

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

This configuration tells Multer:

  • Save files inside uploads/
  • Rename files using current timestamp + original extension

Example:

1712345678901.pdf

3. Create Upload Middleware

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

This creates the upload handler using the defined storage.


4. Build HTML Upload Form

<form action="/upload" method="POST" enctype="multipart/form-data">

Important points:

  • method="POST" → file is sent to server
  • enctype="multipart/form-data" → required for file upload

5. Handle File Upload

app.post("/upload", upload.single("myFile"), (req, res) => {
res.send("File uploaded successfully!");
});
  • upload.single("myFile") handles one file
  • "myFile" must match the input name in form

🎯 IMPORTANT MULTER METHODS

MethodPurpose
upload.single("fieldname")Upload one file
upload.array("fieldname", maxCount)Upload multiple files
upload.fields([...])Upload multiple fields

⚡ ADVANCED VERSION: FILE TYPE VALIDATION

You can restrict uploads to images only.

const upload = multer({
storage: storage,
fileFilter: function (req, file, cb) {
const allowedTypes = /jpg|jpeg|png|pdf/;
const ext = allowedTypes.test(path.extname(file.originalname).toLowerCase());

if (ext) {
cb(null, true);
} else {
cb(new Error("Only JPG, PNG, and PDF files are allowed"));
}
}
});

⚡ ADVANCED VERSION: FILE SIZE LIMIT

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

👉 This limits the upload size to 2 MB.


⚡ EXAMPLE: MULTIPLE FILE UPLOAD

app.post("/upload-multiple", upload.array("myFiles", 3), (req, res) => {
res.send("Multiple files uploaded successfully!");
});

HTML form:

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

📚 REAL-WORLD USE CASE

File upload functionality is used in:

  • Resume upload systems
  • Profile image upload
  • Document submission portals
  • Online assignment submission
  • E-commerce product image upload
  • Student project report upload

❓ VIVA QUESTIONS (IMPORTANT)

Q1. What is Multer in Node.js?

👉 Multer is a middleware used for handling file uploads in Node.js and Express.


Q2. Why is enctype="multipart/form-data" used?

👉 It is required for uploading files through HTML forms.


Q3. What is the purpose of upload.single()?

👉 It is used to upload one file at a time.


Q4. Where are uploaded files stored?

👉 In the folder specified in the destination property, such as uploads/.


Q5. Why is path.extname() used?

👉 It is used to get the original file extension like .jpg, .pdf, etc.


Q6. Can we upload multiple files using Multer?

👉 Yes, using upload.array() or upload.fields().


Q7. Can we restrict file type in Multer?

👉 Yes, using the fileFilter option.


Q8. Can we set file size limits?

👉 Yes, using the limits option in Multer.


🔗 RELATED POSTS

👉 MCA 168 Full Stack Development Lab Programs List
👉 Node.js File Operations – Program 20
👉 React Login Form Validation – Program 19


📌 CONCLUSION

The Node.js File Upload Application is an essential backend program. It teaches how to handle file uploads securely and efficiently using Express and Multer.

👉 Practice single-file upload first, then extend it to multiple files, validation, and size restrictions.


Further Reading

JUnit Tutorial

How to Master Full Stack Development?

Spring Framework Practice Problems and Their Solutions

30 MCQs on JUnit

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

100+ MCQs On Java Architecture

Java Practice Exercise

programmingempire

Princites

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *