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 a...


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>
	

COMMENTS

Nama

Add,1,Ajax,2,ajax tutorial,1,Ajax with javascript,1,Ajax with node.js,1,application,2,array,1,array to string,1,array to string conversion nodejs,1,array to string in node js,1,array to string nodejs,1,Asynchronous JavaScript,1,authentication,1,authentication node js,1,authorization,1,availability,1,backend,1,bootstrap offcanvas dynamic content,1,bootstrap offcanvas dynamic content node.js,1,bootstrap offcanvas dynamic data,1,bootstrap offcanvas remote dynamic content,1,cart,1,centos 7,1,centos7,1,check,1,contact form node js,1,contact form nodemailer,1,contact us form node,1,conversion,1,create,1,crud,4,crud application,1,crud operation in node js,1,crud operation in node js with mysql,1,CSS,1,data,1,database,1,databases,1,datatables,1,DataTables integration in React.js,1,date range,1,delete,2,download,1,drag &amp; drop,1,drag and drop,1,drag and drop files,1,drag and drop multiple file,1,drag n drop,1,dynamic dropdown in react js,1,dynamic dropdown in react.js,1,ecommerce,2,edit,1,educational project,1,email address,1,email verification,1,email verification using jwt,1,express,3,expressjs,1,fetch,1,file upload,1,file upload in node js,1,files,1,filter,1,Front-end development tutorial,1,Frontend,1,GET,1,how to send email using node js,1,how to send emails in node js,1,html,1,html 2 pdf,1,html to pdf,1,html to pdf node,1,insert,2,insert data in mysql node js,1,Javascript,3,JavaScript tutorial,1,join array nodejs,1,js,1,json,1,jwt,3,jwt authentication,2,jwt authentication node js,1,jwt authentication php,1,jwt email verification,1,jwt login,1,jwt login php,1,jwt php example,1,jwt token,1,jwt token email verification,1,laravel 10,1,laravel 10 tutorial,1,laravel datatables,1,laravel datatables date range filter,1,laravel date filter,1,laravel date range filter,1,last insert id in node,1,learn reactjs,1,linux,1,live,2,live check email address availability,1,live search,1,load more data on click,1,load more data on click javascript,1,load more javscript node.js,1,load more nodejs,1,load more results,1,load more results with node js and ajax,1,login,1,merge 2 arrays in node js,1,merge array in nodejs,1,merge array node,1,merge two array in node js,1,MongoDB,1,mongodb crud,1,mongodb crud operations,1,multer,1,multiple file upload,1,mysql,7,mysql 8,1,mysql tutorial,1,mysql8,1,node,3,node js,8,node js array merge,1,node js array to string,1,node js crud,2,node js crud mysql,1,node js crud operation with mysql,1,node js load more pagination,1,node js mongodb crud,1,node js mysql last insert id,1,node js tutorial,2,node mongodb crud,1,node mysql get last insert id,1,node pdf,1,node.js,8,node.js array,1,node.js crud,1,node.js mysql,1,node.js tutorial,2,nodejs,9,nodejs array,1,nodejs array merge,1,nodejs create pdf,1,nodejs crud,1,nodejs pdf,1,nodejs pdf create,1,nodejs programming,1,offcanvas,1,open source,1,Optimizing web application performance,1,parking management system,1,parking management system in php,1,parking management system project,1,password,1,pdf-creator-node,1,php,3,php jwt authentication example,1,php jwt login,1,php login jwt,1,php parking management system,1,php project,1,PHP server-side processing,1,populate dropdown from database,1,programming tutorial,1,project,1,Puppeteer,1,Puppeteer HTML to PDF,1,React,1,react file upload,1,react js,2,react js dynamic dropdown,1,react js file upload validation,1,react js tutorial,1,react php myql,1,React.js,1,react.js dependent select,1,react.js file upload,1,Reactjs,4,reactJS CRUD,1,reactjs file upload,1,reactjs file upload app,1,reactjs file upload sample code,1,reactjs tutorial,1,read,1,register,1,registration,2,remove,1,request form node,1,reset,1,search,1,select,1,send activation email php,1,sending email using node js,1,server,1,Server-side data processing,1,shopping cart,1,shopping cart in node js,1,shopping cart javascript,1,shopping cart project in javascript,1,shopping cart using node js,1,shopping-cart,1,society management system in php,1,society management system php,1,society management system php source code,1,society management system project in php,1,society management system project php,1,source code,1,string,1,token,2,tutorial,8,update,2,using jwt for email verification,1,vanilla,1,vite,1,vitejs,1,vitejs crud app,1,web development,7,Web development guide,1,webslesson,2,what is jwt authentication,1,
ltr
item
kumpulan driver: Nodejs Drag & Drop Multiple File Upload using Multer
Nodejs Drag & Drop Multiple File Upload using Multer
https://i.ytimg.com/vi/sQM8zo2s1O8/hqdefault.jpg
https://i.ytimg.com/vi/sQM8zo2s1O8/default.jpg
kumpulan driver
https://kepsuk.blogspot.com/2024/03/nodejs-drag-drop-multiple-file-upload_8.html
https://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/
http://kepsuk.blogspot.com/2024/03/nodejs-drag-drop-multiple-file-upload_8.html
true
6399859916032798219
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content