📌 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:
- Create an Express server
- Use Multer middleware for file upload
- Create an
uploadsfolder - Build an HTML form with file input
- Submit the file to the server
- Save the uploaded file into the folder
- 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 servermulter→ used for uploading filespath→ 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 serverenctype="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
| Method | Purpose |
|---|---|
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
How to Master Full Stack Development?
Spring Framework Practice Problems and Their Solutions
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
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
