Saturday 22 June 2024

Building an Online Doctor Appointment System with Node.js, Express, and MongoDB

Building an Online Doctor Appointment System with Node.js, Express, and MongoDB

In this tutorial, we will walk you through the development of a comprehensive Online Doctor Appointment System. This system is designed to simplify the process of booking and managing doctor appointments for both healthcare providers and patients. By leveraging modern web technologies and a robust backend, this system ensures efficient management, secure authentication, and a seamless user experience.

Introduction


Why Build an Online Doctor Appointment System?


In today's fast-paced world, managing appointments manually can be both cumbersome and inefficient. An Online Doctor Appointment System offers a streamlined solution, enabling healthcare providers to manage their schedules effectively and allowing patients to book appointments with ease. This system helps in reducing no-show rates, improving patient satisfaction, and optimizing the utilization of healthcare resources.

Key Benefits


  1. Efficiency: Automates the appointment scheduling process, reducing administrative overhead.
  2. Accessibility: Patients can book appointments 24/7 from the comfort of their homes.
  3. Better Resource Management: Helps healthcare providers manage their schedules and patient load effectively.
  4. Reduced Waiting Times: Allows patients to see real-time availability and choose suitable slots, reducing waiting times.
  5. Enhanced Communication: Sends notifications and reminders to patients, improving engagement and adherence.




System Overview


The Online Doctor Appointment System consists of three main user roles: Admin, Doctor, and Patient. Each role has distinct functionalities tailored to their specific needs.

Admin Side


  • Admin Login using JWT Token: Secure authentication.
  • View Analytics Data: Dashboard showing system analytics.
  • Manage Doctor Data: Add, edit, enable, disable doctors.
  • View Patient Data: Access and manage patient details.
  • Manage Doctor Availability: Add, edit, delete doctor schedules.
  • Manage Appointments: View and update appointment details.
  • Profile Management: Admin can edit their profile.
  • Logout: Securely log out of the system.

Doctor Side


  • Doctor Login using JWT Token: Secure authentication.
  • View Appointments: Access appointments specific to the logged-in doctor.
  • Manage Appointments: Add comments and update appointment status.
  • Profile Management: Doctors can edit their profiles.
  • Logout: Securely log out of the system.

Patient Side


  • Patient Registration with Email Verification: New patients can register and verify their email.
  • Patient Login using JWT Token: Secure authentication.
  • View Doctor Availability: Check available slots for doctors.
  • Book an Appointment: Schedule an appointment with a doctor.
  • Manage Appointments: View, download, and manage their appointments.
  • Profile Management: Patients can edit their profiles.
  • Logout: Securely log out of the system.

Technologies Used


Server-Side


  • Node.js: A powerful JavaScript runtime that enables server-side scripting.
  • Express.js: A flexible Node.js web application framework for building robust APIs.
  • MongoDB: A NoSQL database known for its scalability and flexibility in managing large volumes of data.

Client-Side


  • Vanilla JavaScript: Used for client-side logic and interactivity.
  • jQuery: Simplifies HTML document traversal, event handling, and AJAX interactions.
  • jQuery DataTables: Enhances HTML tables with advanced interaction controls.
  • Bootstrap 5: A responsive and modern CSS framework for designing user-friendly interfaces.
  • HTML 5: Provides the structural foundation of the web pages.

Node.js Libraries


  • express: The core web application framework for handling HTTP requests and routing.
  • mongoose: An ODM (Object Data Modeling) library for MongoDB and Node.js.
  • jsonwebtoken: For creating and verifying JSON Web Tokens (JWT) for secure authentication.
  • joi: A powerful schema description language and data validator for JavaScript.
  • multer: Middleware for handling multipart/form-data, useful for file uploads.
  • bcrypt: A library to help hash passwords securely.
  • moment-timezone: For manipulating and formatting dates in different time zones.
  • nodemailer: A module for sending emails from Node.js applications.
  • puppeteer: A Node library that provides a high-level API to control headless Chrome or Chromium, useful for generating PDFs.




Conclusion


This tutorial covered the development of an Online Doctor Appointment System using Node.js, Express, and MongoDB. We explored user authentication, CRUD operations, PDF generation, email notifications, and more. By following these steps, you can build a robust and scalable appointment management system for healthcare providers.





Demo of Online Doctor Appointment Booking System





Introduction to Cloud-Based Web Scraping

Introduction to Cloud-Based Web Scraping

In-house vs. cloud-based web scraping, what would you opt for? Perhaps in-house scraping because of the level of control you have over the scraping process. Moreover, you might prefer to keep the entire scraping process in-house to ensure the highest level of privacy and data security.

Yes, in-house scraping offers greater control, privacy, and security. However, maintaining and scaling in-house web scraping is less feasible. Setting up an in-house scraping operation is also costly. And this is where cloud-based web scraping comes in to save the day.

Let’s explore how cloud-based web scraping solves these in-house web scraping issues. The solutions also count as the reasons to consider cloud-based web scraping.

Why Cloud-Based Web Scraping?


1. Scalability and efficiency


Compared to an in-house setup that's limited to specific hardware configurations, a cloud-based setup gives you access to vast on-demand computing power. This means you can downscale or upscale as desired, optimizing costs and ensuring optimal performance.

In addition to the liberty to scale, you don’t have to worry about hardware and software upgrades. The cloud provider eliminates the need to constantly invest in infrastructure upgrades, allowing you to focus on making payments for the valuable resources to achieve scraping objectives.

2. Accessibility and collaboration


Do you have access to a stable internet connection? Then, you can access your scraped data on any device and from anywhere. This eliminates the need for physical data transfers, empowering remote collaborations.

Any team member can access the scraping project, and share and analyze the scraped data without traveling to a central in-house repository. Do not worry. Most cloud-based web scraping tools offer robust security measures to safeguard your data.

3. Reduced maintenance and ease of use


As mentioned, the cloud provider manages the underlying web scraping infrastructure. This includes software updates, server upkeep, and fine-tuning general operations to ensure scraping engines are running smoothly. Your task is to define clear scraping goals, utilize the available resources, and make good use of the extracted data.

Besides reduced maintenance, cloud providers fit web scraping services with intuitive interfaces to streamline the scraping process. They grant you access to pre-built templates and scrapers, as well as options to build scrapers with minimal to no coding experience, easing the whole web scraping process.

4. Avoiding IP blocks


One of the most frustrating aspects of web scraping is IP blocks, especially now that several websites have implemented anti-scraping mechanisms. To deal with this issue, you must lease a pool of IP addresses to work with.

In most cases, leasing a pool of IP addresses from a proxy provider becomes costly over time, limiting scraping operations. With a cloud-based scraping setup, you rarely worry about leasing IP addresses. Most cloud providers have a vast pool of constantly rotating IP addresses to bypass IP blocks.

5. Cost-Effectiveness for occasional use


Cloud-based web scraping solutions operate on a pay-as-you-go pricing structure. So, you only pay for the resources used for a specified period. This model makes cloud-based web scraping much more cost-effective for occasional use.

Some cloud providers offer free-tier access to scraping resources. This allows you to try their services before committing, significantly optimizing cost. Moreover, if you want to run a small web scraping project, you can use the free trial before scaling the project, saving you more.

Overall, cloud-based scraping services come in different flavors, and the specific way they work varies, ultimately varying the cost saved, too! Here are popular services to choose from:

Popular Cloud-Based Web Scraping Setups or Services


1. Visual web scraping tools


Visual web scraping tools eliminate the complexities of web scraping. Rather than writing complex scripts, the cloud provider allows you access to a visual scraping tool. The tool has an intuitive point-and-click interface, letting you simply navigate the website you want to scrape and select the elements you want to extract.

Even though visual web scraping tools are suitable for beginners and those with limited coding experience, you can use them to accomplish complex scraping tasks.

Hidden, from your view, is a set of complex scraping algorithms that automatically generate the complex scraping scripts required to navigate the target website and retrieve various data points.

2. Web scraping APIs


Compared to visual web scraping tools, web scraping APIs require you to have technical know-how. You should be able to write scripts that can interact with the scraping APIs and instruct them to take the wheel and handle the scraping process.

Think of a web scraping API (Application Programming Interface) as a special toolkit for developers to build custom scraping solutions. So, you are required to customize it to your liking so that it can dispatch virtual browsers to visit a target site and extract data based on your instructions.

3. Hybrid solutions


If you are well-versed in writing web scraping scripts but still love the simplicity of a point-and-click interface, a hybrid web scraping solution is for you.

Hybrid solutions integrate a user-friendly interface with drag-and-drop functionality. So, you can build an essential web scraping tool by visually selecting the data you want to extract from a web page. And, whenever you want to extract data from a complex-structured site or require advanced data manipulation, you can switch to coding.

4. Managed scraping services


From setting up to managing the whole web scraping process, a managed scraping service takes care of everything. This service is ideal for high-volume scraping needs. It removes the worry of building a team to handle the scraping technical intricacies while you reap the benefits of the obtained data.

With little to no technical elements to handle, your in-house team can focus on building the business's core functionalities. The cloud-based service provider becomes your scraping partner, taking care of the technical part and delivering the required data in a usable format.

Closing Words


Web scraping powers lead generation, price monitoring, market research, academic research, and more business elements. However, the burning question is — How should you set up your web scraping operation? In-house or on the cloud. Use this blog post as a guide to making the correct decision.

Monday 27 May 2024

PHP 8 MySQL Project on Online Examination System


The advent of digital technologies has revolutionized various aspects of education, including examination systems. Traditional paper-based exams are increasingly being replaced by online examination systems, which offer numerous advantages such as efficiency, accuracy, and accessibility. In this article, we will explore the development of an online examination system using PHP 8 and MySQL, focusing on the features for three types of users: Admin, Sub User, and Student.

PHP 8 MySQL Project on Online Examination System




Key Features of the Online Examination System


Our online examination system is designed to cater to the needs of different users within the educational ecosystem. The system includes comprehensive features for admins, sub-users (such as teachers or moderators), and students, ensuring a seamless and efficient examination process.

Admin User Features


The Admin user has the highest level of control within the system, responsible for managing classes, subjects, students, exams, and sub-users. Here are the detailed functionalities available to the Admin:

  • Class Management: Admins can add, edit, disable, or enable class data, allowing them to organize students into different educational levels or groups.
  • Subject Management: Admins can manage subject data, including adding new subjects, editing existing ones, and enabling or disabling subjects as needed.
  • Subject Assignment: Admins can assign subjects to specific classes, edit these assignments, and delete any outdated or incorrect assignments.
  • Student Management: Admins can handle student data comprehensively by adding new students, editing details, and enabling or disabling students' statuses.
  • Student Class Assignment: Admins can assign students to classes, edit these assignments, and control the activation status of these assignments.
  • Exam Management: Admins can create, edit, and delete exam data, ensuring that the examination schedules and details are up-to-date.
  • Exam Subject Management: Admins can add, edit, and delete exam subject data, allowing for precise control over which subjects are included in each exam.
  • Exam Question Management: Admins can manage exam questions, including adding new questions, editing existing ones, and removing outdated questions.
  • Sub User Management: Admins can manage sub-user data by adding, editing, disabling, or enabling sub-user accounts.




Sub User Features


Sub-users, such as teachers or moderators, have access to functionalities that allow them to manage exams and related data. Their capabilities include:

  • Exam Management: Sub-users can add, edit, and delete exam data, assisting in the organization and scheduling of exams.
  • Exam Subject Management: Sub-users can manage the subjects related to each exam, ensuring that all necessary subjects are included.
  • Exam Question Management: Sub-users can add, edit, and delete exam questions, contributing to the creation of comprehensive question banks.

Student User Features


Students are the primary users of the online examination system. Their experience is designed to be straightforward and user-friendly, providing the following features:

  • Login: Students can securely log in to the system using their credentials.
  • View Exam Details: Students can view details of upcoming exams, including subjects, schedules, and instructions.
  • Participate in Exams: Students can take part in exams directly through the system, answering questions and submitting their responses online.
  • View Exam Results: After completing an exam, students can view their results, including scores and feedback, if provided.

Developing the System with PHP 8 and MySQL


PHP 8 brings numerous improvements and new features to the table, making it an excellent choice for developing robust web applications. Coupled with MySQL, a powerful relational database management system, developers can create efficient and scalable online examination systems.

Setting Up the Environment


To start, ensure you have a web server (such as Apache or Nginx) and a MySQL server installed on your development machine. You will also need PHP 8 installed, along with necessary extensions like PDO for database interactions.

Database Design


Designing the database is a critical step. The database should include tables for users (admin, sub-users, and students), classes, subjects, exams, exam subjects, and questions. Each table should be normalized to reduce redundancy and ensure data integrity.

Implementing the Admin Features


For the admin features, create CRUD (Create, Read, Update, Delete) operations for classes, subjects, students, exams, and sub-users. Use PHP to handle server-side logic and MySQL to store and retrieve data. Implement user authentication and role-based access control to ensure only authorized users can perform certain actions.

Developing the Sub User and Student Interfaces


For sub-users, implement interfaces that allow them to manage exams and questions. Ensure they have a restricted set of permissions compared to admins. For students, develop a user-friendly interface where they can log in, view exams, participate in them, and see their results. Use AJAX for smooth interactions and real-time updates.

Security Considerations


Security is paramount in an online examination system. Implement robust authentication and authorization mechanisms, protect against SQL injection by using prepared statements, and ensure data is transmitted over HTTPS to prevent eavesdropping.





Conclusion


Developing an online examination system with PHP 8 and MySQL involves careful planning and execution. By providing distinct features for admins, sub-users, and students, the system ensures a smooth and efficient examination process. With PHP 8's new features and MySQL's reliability, this system can handle the demands of modern educational institutions, offering a scalable and secure solution for online examinations.





Sunday 5 May 2024

Building a Real-Time Chat Application Project in Node JS with MongoDB


In today's fast-paced digital world, real-time communication has become a necessity for many applications. Whether it's collaborating with team members, providing customer support, or simply connecting friends and family, the demand for real-time chat applications is ever-growing. In this article, we'll delve into the process of building a real-time chat application using Node.js and MongoDB, two powerful technologies that complement each other seamlessly.


Building a Real-Time Chat Application Project in Node JS with MongoDB




Why Node.js and MongoDB?


Node.js is a popular runtime environment for building scalable and efficient server-side applications. Its event-driven architecture and non-blocking I/O make it an excellent choice for real-time applications such as chat. MongoDB, on the other hand, is a flexible and scalable NoSQL database that stores data in JSON-like documents, making it well-suited for handling the unstructured data typically found in chat applications.





Feature of Chat Application


1. User Registration


User registration allows individuals to create an account on your chat application. To implement this feature:

  • Create User Schema: Use Mongoose to define a schema for users. Include fields such as username, email, password (hashed using bcrypt), profile picture, and any other relevant information.
  • Registration Endpoint: Set up an endpoint in Express to handle user registration requests. Validate incoming data using Joi, hash the password using bcrypt, and then save the user data to MongoDB using Mongoose.
  • User Authentication: Upon successful registration, generate a JWT token using jsonwebtoken and send it back to the client. This token will be used for subsequent authentication.

2. User Login using JSON Web Token


User login allows registered users to authenticate themselves and access the chat application. Here's how to implement it:

  • Login Endpoint: Create an endpoint to handle user login requests. Validate the user's credentials (username/email and password), compare the hashed password with the stored hash in the database, and if they match, generate a JWT token and send it back to the client.
  • Token Storage: Store the JWT token securely on the client-side (e.g., in local storage or cookies) to be sent along with subsequent requests for authentication.
  • Middleware for Authentication: Create a middleware function in Express to verify the JWT token on protected routes. If the token is valid, allow access to the requested resource; otherwise, return a 401 Unauthorized error.

3. Edit User Profile Data with Image Upload


This feature enables users to update their profile information, including uploading a new profile picture. Here's how to implement it:

  • Profile Update Endpoint: Create an endpoint to handle profile update requests. Allow users to update fields such as username, email, bio, etc. For profile picture updates, use Multer to handle file uploads and save the image to a designated folder.
  • Link Profile Picture to User: Store the file path or URL of the uploaded profile picture in the user document in MongoDB.
  • Secure File Uploads: Implement validation and security measures to prevent unauthorized file uploads and ensure that only allowed file types and sizes are accepted.

4. Search User


This feature allows users to search for other users within the chat application. Here's how to implement it:

  • Search Endpoint: Create an endpoint to handle user search queries. Accept search parameters such as username or email and query the user database in MongoDB to find matching users.
  • Return Search Results: Send the list of matching users back to the client as a response.

5. Display Search Request Notification


When a user receives a search request, they should be notified. Here's how to implement it:

  • Real-Time Notifications: Use Socket.io to emit a notification event to the recipient user when they receive a search request.
  • Display Notification: Implement client-side logic to display the notification to the user in real-time, such as using toast notifications or updating the UI dynamically.

6. Accept Search Request


This feature allows users to accept incoming search requests. Here's how to implement it:

  • Accept Request Endpoint: Create an endpoint to handle requests to accept incoming search requests. Update the status of the search request in the database to indicate acceptance.
  • Real-Time Updates: Emit a notification event to the sender of the search request to inform them that their request has been accepted.

7. List Accepted Search Request User


Users should be able to see a list of users who have accepted their search requests. Here's how to implement it:

  • List Accepted Requests Endpoint: Create an endpoint to retrieve a list of users who have accepted the current user's search requests.
  • Return Accepted Users: Send the list of accepted users back to the client as a response.

8. Start Chat with other User


This feature enables users to initiate a chat with other users. Here's how to implement it:

  • Chat Initiation Endpoint: Create an endpoint to handle requests to start a chat with another user. Store the chat information in the database, including the participants and any initial messages.
  • Real-Time Chat: Use Socket.io to establish real-time communication between users in the chat. Emit events for sending and receiving messages, typing indicators, etc.

9. Display User Online Offline Status


Users should be able to see the online/offline status of other users. Here's how to implement it:

  • Real-Time Status Updates: Use Socket.io to emit events for updating the online/offline status of users in real-time.
  • Update User Status: Implement logic on the server-side to update the user's status in the database based on their activity (e.g., logging in/out).

By implementing these features, you can create a comprehensive and user-friendly chat application that provides a seamless communication experience for your users.





Setting Up the Environment


Before we start building our chat application, let's ensure we have Node.js and MongoDB installed on our system. Once installed, we can create a new directory for our project and initialize a new Node.js project using npm.

	
		mkdir node-chat
		cd node-chat
	

Next, let's install the necessary dependencies:

1. Express


	
		npm install express
	

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building web servers and handling HTTP requests by providing a simple and intuitive API.

In our chat application, we use Express to:

  • Set up our server and define routes for handling HTTP requests.
  • Serve static files such as HTML, CSS, and client-side JavaScript.
  • Implement middleware for parsing incoming request bodies and handling errors.

2. Multer


	
		npm install multer
	

Multer is a middleware for handling multipart/form-data, which is primarily used for uploading files. While our chat application may not require file uploads, it's a good practice to include Multer for handling any future enhancements that may involve file uploads.

3. Mongoose


	
		npm install mongoose
	

Mongoose is an elegant MongoDB object modeling tool designed to work in an asynchronous environment. It provides a straightforward schema-based solution to model application data, validate incoming data, and perform CRUD operations on MongoDB databases.

In our chat application, Mongoose helps us:

  • Define schemas for our MongoDB documents, such as user profiles and chat messages.
  • Create models based on these schemas to interact with the MongoDB database.
  • Perform data validation and define relationships between different types of data.

4. Joi


	
		npm install joi
	

Joi is a powerful schema description language and data validator for JavaScript. It allows us to define schemas for the data our application expects to receive, validate incoming data against these schemas, and provide helpful error messages if validation fails.

In our chat application, Joi can be used to:

  • Validate incoming requests to ensure that they contain the expected data in the correct format.
  • Sanitize and coerce incoming data to ensure consistency and security.
  • Handle validation errors gracefully and provide meaningful feedback to the user.

5. Bcrypt


	
		npm install bcrypt
	

Bcrypt is a widely-used library for hashing passwords in Node.js applications. It provides a secure way to hash passwords before storing them in the database, making it difficult for attackers to reverse-engineer passwords even if they gain access to the database.

In our chat application, Bcrypt is essential for:

  • Hashing user passwords before storing them in the database to protect user accounts from unauthorized access.
  • Comparing hashed passwords during the authentication process to verify the identity of users.

6. Jsonwebtoken


	
		npm install jsonwebtoken
	

Jsonwebtoken is a library for generating and verifying JSON Web Tokens (JWTs) in Node.js applications. JWTs are a compact and self-contained way of representing claims between parties, making them ideal for authentication and information exchange.

In our chat application, Jsonwebtoken is used for:

  • Generating JWTs when users successfully authenticate with the server.
  • Verifying JWTs when users make requests to protected routes, ensuring that they are authorized to access the requested resources.

By leveraging these libraries in our chat application, we can ensure that our application is secure, efficient, and scalable, while also providing a seamless user experience.

Conclusion


In this article, we've covered the process of building a real-time chat application using Node.js and MongoDB. By leveraging the power of Socket.io for real-time communication and MongoDB for data storage, we've created a scalable and efficient chat application that can handle a large number of users simultaneously. With some additional features and enhancements, you can further customize and extend this application to meet your specific requirements.

Beyond its practical applications, this Node.js chat application project can serve as a valuable educational resource for students and by incorporating this Node.js chat application project into educational curricula or as part of self-directed learning, students can gain practical experience in building real-world applications while reinforcing core concepts in web development, software engineering, and computer science. Whether used as a standalone project or as part of a larger curriculum, this project offers a valuable opportunity for hands-on learning and skill development.





Friday 8 March 2024

Nodejs Drag & Drop Multiple File Upload using Multer


Introduction:


In today's digital world, file uploading is a common functionality for web applications. Node.js, with its asynchronous and event-driven architecture, offers an excellent platform for handling file uploads efficiently. Multer, a middleware for Express.js, simplifies the process of handling multipart/form-data, making it perfect for handling multiple file uploads.

In this tutorial, we will explore how to implement drag and drop multiple file uploads using Node.js and Multer, ensuring the content is optimized for search engines.


Node.js Drag & Drop Multiple File Upload using Multer


Table of Contents:


  1. Setting up the Project Environment
  2. Installing Dependencies
  3. Configuring Multer Middleware
  4. Creating the Frontend Interface
  5. Implementing Drag and Drop Functionality
  6. Handling File Uploads on the Server
  7. Run Application
  8. Conclusion

1. Setting up the Project Environment:


Before diving into the code, let's ensure we have Node.js installed on our system. If not, download and install it from the official Node.js website.

	
	mkdir drag-drop
	cd drag-drop
	

2. Installing Dependencies:


Initialize a new Node.js project and install the required dependencies using npm:

	
	npm init -y
	npm install express multer
	

3. Configuring Multer Middleware:


Create an Express.js server under server.js and configure Multer middleware to handle file uploads:

server.js
	
	const express = require('express');
	const multer = require('multer');
	const path = require('path');
	const app = express();
	const PORT = 3000;
	app.use(express.static(__dirname));

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

	// Initialize Multer upload
	const upload = multer({storage : storage});
	
	app.get('/upload', async (request, response) => {
		response.sendFile(__dirname + '/upload.html');
	});
	
	app.listen(PORT, () => {
		console.log(`Server is running on port ${PORT}`);
	});
	

4. Creating the Frontend Interface:


Design a simple HTML page with name upload.html file with drag and drop functionality for uploading files:

upload.html
	
	<!doctype html>
	<html lang="en">
		<head>
			<!-- Required meta tags -->
			<meta charset="utf-8">
			<meta name="viewport" content="width=device-width, initial-scale=1">

			<!-- Bootstrap CSS -->
			<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

			<title>Drag and Drop File Upload</title>
		</head>
		<body>
			
			<div class="container">
				<h1 class="text-center mb-5 mt-5"><b>Drag and Drop File Upload in Node.js</b></h1>

				<div id="drop_zone">
					<p>Drag and drop files here</p>
				</div>
				<br />
				<div class="card mb-5">
					<div class="card-header">
						<div class="row">
							<div class="col col-6">Uploaded File</div>
							<div class="col col-6"></div>
						</div>
					</div>
					<div id="uploadedImage" class="card-body">

					</div>
				</div>
			</div>
			<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
		</body>
	</html>

	<style>
	#drop_zone {
			width: 100%;
			min-height: 200px;
			border: 2px dashed #ccc;
			border-radius: 10px;
			padding: 20px;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
		}
		#drop_zone.hover {
			background-color: #f0f0f0;
		}
	</style>
	

5. Implementing Drag and Drop Functionality:


Write JavaScript code in uplode.html file to handle drag and drop functionality:

upload.html
	
	<script>

	var dropZone = document.getElementById('drop_zone');

	dropZone.addEventListener('dragover', (event) => {
		event.preventDefault();
		dropZone.classList.add('hover');
	});

	dropZone.addEventListener('dragleave', (event) => {
		event.preventDefault();
		dropZone.classList.remove('hover');
	});

	dropZone.addEventListener('drop', (event) => {
		event.preventDefault();
		dropZone.classList.remove('hover');
		var files = event.dataTransfer.files;
		handlesFiles(files);
	});

	function handlesFiles(files){
		for(var count = 0; count < files.length; count++){
			var file = files[count];
			uploadFile(file);
		}
	}

	function uploadFile(file){
		var formData = new FormData();
		formData.append('file', file);
		fetch('/upload', {
			method : 'POST',
			body : formData
		})
		.then(response => response.json())
		.then(data => {
			const gallery = document.getElementById('uploadedImage');
			let html = `<img src="/uploads/${data.filename}" class="img-thumbnail" />`;
			gallery.innerHTML = gallery.innerHTML + html;
		});
	}

	</script>
	

6. Handling File Uploads on the Server:


Now in server.js, we have to handle file uploads on the server-side using Express.js:

server.js
	
	app.post('/upload', upload.single('file'), (request, response) => {
		response.json({ filename : request.file.filename });
	});
	

7. Run Application


After writing all above code, for run this node application in browser, we have to start node server, so we have goes to terminal window, and there we have to run node server.js command which will start node development server.

And at browser, we have to open http://localhost:3000 url, then it will open this Node Drag and Drop application in browser.

8. Conclusion:


Congratulations! You've successfully implemented drag and drop multiple file uploads using Node.js and Multer. This tutorial covered the setup of the project environment, installation of dependencies, configuration of Multer middleware, creation of the frontend interface, implementation of drag and drop functionality, handling file uploads on the server, and displaying upload progress.

Complete Source Code


server.js
	
	const express = require('express');
	const multer = require('multer');
	const path = require('path');
	const app = express();
	const PORT = 3000;
	app.use(express.static(__dirname));

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

	// Initialize Multer upload
	const upload = multer({storage : storage});

	app.get('/upload', async (request, response) => {
		response.sendFile(__dirname + '/upload.html');
	});

	app.post('/upload', upload.single('file'), (request, response) => {
		response.json({ filename : request.file.filename });
	});

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

upload.html
	
	<!doctype html>
	<html lang="en">
		<head>
			<!-- Required meta tags -->
			<meta charset="utf-8">
			<meta name="viewport" content="width=device-width, initial-scale=1">

			<!-- Bootstrap CSS -->
			<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

			<title>Drag and Drop File Upload</title>
		</head>
		<body>
			
			<div class="container">
				<h1 class="text-center mb-5 mt-5"><b>Drag and Drop File Upload in Node.js</b></h1>

				<div id="drop_zone">
					<p>Drag and drop files here</p>
				</div>
				<br />
				<div class="card mb-5">
					<div class="card-header">
						<div class="row">
							<div class="col col-6">Uploaded File</div>
							<div class="col col-6"></div>
						</div>
					</div>
					<div id="uploadedImage" class="card-body">

					</div>
				</div>
			</div>
			<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
		</body>
	</html>

	<style>
	#drop_zone {
			width: 100%;
			min-height: 200px;
			border: 2px dashed #ccc;
			border-radius: 10px;
			padding: 20px;
			box-sizing: border-box;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
		}
		#drop_zone.hover {
			background-color: #f0f0f0;
		}
	</style>

	<script>

	var dropZone = document.getElementById('drop_zone');

	dropZone.addEventListener('dragover', (event) => {
		event.preventDefault();
		dropZone.classList.add('hover');
	});

	dropZone.addEventListener('dragleave', (event) => {
		event.preventDefault();
		dropZone.classList.remove('hover');
	});

	dropZone.addEventListener('drop', (event) => {
		event.preventDefault();
		dropZone.classList.remove('hover');
		var files = event.dataTransfer.files;
		handlesFiles(files);
	});

	function handlesFiles(files){
		for(var count = 0; count < files.length; count++){
			var file = files[count];
			uploadFile(file);
		}
	}

	function uploadFile(file){
		var formData = new FormData();
		formData.append('file', file);
		fetch('/upload', {
			method : 'POST',
			body : formData
		})
		.then(response => response.json())
		.then(data => {
			const gallery = document.getElementById('uploadedImage');
			let html = `<img src="/uploads/${data.filename}" class="img-thumbnail" />`;
			gallery.innerHTML = gallery.innerHTML + html;
		});
	}

	</script>