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>
	

0 comments:

Post a Comment