Showing posts with label CSS. Show all posts
Showing posts with label CSS. Show all posts

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>
	

Wednesday, 26 October 2016

Table Column and Row Highlight by using Jquery CSS

Hello friends in this tutorial we are going to learn simple but very useful concept in web development. Here we will discussing on how to change the background color of table row and column on mouse hover on table row and column by using Javascript library jquery and CSS. In this Jquery tutorial, we will highlight table column and row on mouse hover event. In Jquery there are several event for highlight table column and row. Here we will use jquery hover event for change background color of table column and row on same time. Under this hover() method. We will add or remove css class on mouse enter or mouse leave event of hover() method. Here we have simply fetch data from database and display that data under html table. In html table all table row has same class name for jquery selector and in different table column we have define different class name to table column. This way we have make html table structure for highlight table row and column on mouse over on particular table data. In jquery code we have use simple addClass() method and removeClass() method for highlight table column and row. Here addClass() method will add css class to particular element and it will highlight that element and by using removeClass() method, it will remove css class from particular element. This way we can highlight table column and row by using jquery code. By using this functionality into our web project we can easily identify large amount of data by highlighting table row and column.





Source Code



 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $query = "SELECT * FROM tbl_student ORDER BY student_id DESC";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Table Column and Row Highlight by using Jquery CSS</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>       
           <style>  
           .change_table_row  
           {  
                background-color:#f1f1f1;  
           }  
           </style>  
      </head>  
      <body>  
           <div class="container">  
                <h1 align="center">Table Column and Row Highlight by using Jquery CSS</h1><br />  
                <table class="table table-bordered">  
                     <tr bgcolor="#f1f1f1">  
                          <th width="10%" class="table-data1">ID</th>  
                          <th width="55%" class="table-data2">Student Name</th>  
                          <th width="35%" class="table-data3">Student Phone</th>  
                     </tr>  
                     <?php  
                     while($row = mysqli_fetch_array($result))  
                     {  
                     ?>  
                     <tr class="table-row">  
                          <td class="table-data1"><?php echo $row["student_id"]; ?></td>  
                          <td class="table-data2"><?php echo $row["student_name"]; ?></td>  
                          <td class="table-data3"><?php echo $row["student_phone"]; ?></td>  
                     </tr>  
                     <?php  
                     }  
                     ?>  
                </table>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('.table-row').hover(function(){  
           $(this).addClass('change_table_row');  
      }, function(){  
           $(this).removeClass('change_table_row');  
      });  
      var class_name = '';  
      $('th').hover(function(){  
           class_name = $(this).attr('class');  
           $('.'+class_name).addClass('change_table_row');  
      }, function(){  
           $('.'+class_name).removeClass('change_table_row');  
      });  
      $('td').hover(function(){  
           class_name = $(this).attr('class');  
           $('.'+class_name).addClass('change_table_row');  
      }, function(){  
           $('.'+class_name).removeClass('change_table_row');  
      });  
 });  
 </script>  

Saturday, 9 July 2016

How to Make Horizontal Menu using CSS and JQuery

Source Code


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to Make Horizontal Menu using CSS and JQuery</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
                body{  
                     color:#333;  
                     font-family:arial;  
                }  
                .wrapper{  
                     width:540px;  
                     margin:0 auto;  
                }  
                .nav{  
                     margin:0;  
                     padding:0;  
                     list-style:none;  
                }  
                .nav li{  
                     float:left;  
                     width:180px;  
                     position:relative;  
                }  
                .nav li a{  
                     background:#333;  
                     color:#fff;  
                     display:block;  
                     padding:12px 16px;  
                     text-decoration:none;  
                     border-top:1px solid #069;  
                }  
                .nav li a:hover{  
                     color:#069;  
                }  
                .nav ul{  
                     display:none;  
                     list-style:none;  
                     padding:0;  
                }  
           </style>  
           <script>  
           $(document).ready(function(){  
                $('.nav li').hover(function(){  
                     $('ul', this).fadeToggle();  
                });  
           });  
           </script>  
      </head>  
      <body>  
           <div class="wrapper">  
                <ul class="nav">  
                     <li><a href="#">Home</a></li>  
                     <li>       
                          <a href="#">Services</a>  
                          <ul>  
                               <li><a href="#">Consulting</a></li>  
                               <li><a href="#">Sales</a></li>  
                               <li><a href="#">Support</a></li>  
                          </ul>  
                     </li>  
                     <li>  
                          <a href="#">About Us</a>  
                          <ul>  
                               <li><a href="#">Company</a></li>  
                               <li><a href="#">Mission</a></li>  
                               <li><a href="#">Contact Information</a></li>  
                          </ul>  
                     </li>  
                </ul>  
           </div>  
      </body>  
 </html>  

Wednesday, 6 July 2016

Sliding Text on Images by using Jquery

Source Code


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Sliding Text on Images by using Jquery</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <style>  
      #back_image  
      {  
           background:url("beach.jpg");  
           width:1170px;  
           height:657px;  
           position:relative;  
      }  
      #vertical_text  
      {  
           position:absolute;  
           width:1170px;  
           bottom:0;  
           padding:30px 0;  
           background-color:rgba(37, 34, 34, 0.6);  
           font-size:36px;  
           text-transform:uppercase;  
           color:#fff;  
           text-align:center;  
           display:none;  
      }  
      </style>  
      <body>  
           <br /><br />  
           <div class="container">  
                <h1>Sliding Text on Images by using Jquery</h1><br />                 
                <div id="back_image">  
                     <div id="vertical_text">Natural Beach</div>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#back_image').hover(function(){  
           $('#vertical_text').slideToggle('slow');  
      });  
 });  
 </script>  

Sunday, 3 July 2016

Displaying text in Vertical Direction by using CSS


Friends you have most of show text in Horizontal direction and display text in this direction is very easy but if you want to displaying text in vertical direction, then at that time it is not simple to displaying text in vertical direction using css. Displaying text in vertical direction will the visibility of you web page and user can find something new from your website. For describing this things I have place one image to background of web page and on that image I will displaying text in vertical direction using CSS. For displaying text in vertical direction I will use css transform property. This property will transform the text to 2D and 3D transformation. I have using CSS property which rotate the tag line text with ninety degree angle left to display it in vertical direction. And we used a transparent tagline to display the vertical caption for the background. If you want to get information in detail for how can we display text in vertical direction on web pageby using css, so watch web development video tutorial which I attach with this post.

Source Code


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Displaying text in Vertical Direction by using CSS</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <style>  
      #back_image  
      {  
           background:url("beach.jpg");  
           width:1170px;  
           height:657px;  
      }  
      #vertical-text  
      {  
           float:left;  
           transform:rotate(90deg);  
           transform-origin:left top 0;  
           margin-left:80px;  
           padding:10px;  
           background-color:rgba(37, 34, 34, 0.3);  
           font-size:36px;  
           text-transform:uppercase;  
           color:#fff;  
      }  
      </style>  
      <body>  
           <br /><br />  
           <div class="container">  
                <h1>Displaying text in Vertical Direction by using CSS</h1><br />                 
                <div id="back_image">  
                     <div id="vertical-text">Natural Beach</div>  
                </div>  
           </div>  
      </body>  
 </html>  

Saturday, 7 May 2016

How to Auto Resize a textarea html field by jQuery


This one more post on Web Development using JQuery, in this post we will discuss on auto resize of a html textarea field by using jquery. When user start type in html textarea element then it will automatically increase it's height very smoothly and when user will leave from textarea field it will automatically reduce the height smoothly and comes to it's orignal height. This all things are done by using jquery. By using jquery we can change the height of this fields. If you have use facebook and in facebook you have try type in textarea it was automatically change the height. If you want to give somethings new to your user then you can add this type of features in your web application. If you want to learn in details, you can see the video of this post.

Source Code


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to Auto Resize a textarea with jQuery</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
           .wrapper{  
                width:500px;  
                margin:0 auto;  
           }  
           .resize{  
                height:40px;  
                padding:4px;  
                font-size:14px;  
                border:1px solid #dddddd;  
                width:100%;  
                border-radius:5px;  
           }  
           </style>  
           <script>  
           $(document).ready(function(){  
                $('.resize').focus(function(){  
                     $(this).animate({"height":"100px",}, "fast");  
                });  
                $('.resize').blur(function(){  
                     $(this).animate({"height": "40px",}, "fast" );  
                });  
           });  
           </script>  
      </head>  
      <body>  
           <div class="wrapper" align="center">  
                <br />  
                <h3>How to Auto Resize a textarea with jQuery</h3><br />  
                <textarea name="resize" class="resize"></textarea>  
                <br />  
           </div>  
      </body>  
 </html>  

Thursday, 5 May 2016

Stylish Switch Button using CSS3 and Jquery


Source Code




 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Stylish Switch Button using CSS3 and Jquery</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
           .wrapper{  
                width:500px;  
                margin:0 auto;  
           }  
           .switch{  
                width:200px;  
                height:100px;  
                background:#E5E5E5;  
                z-index:0;  
                margin:0;  
                padding:0;  
                appearance:none;  
                border:none;  
                cursor:pointer;  
                position:relative;  
                border-radius:100px;  
           }  
           .switch:before{  
                content: ' ';  
                position:absolute;  
                left:5px;  
                top:5px;  
                width:190px;  
                height:90px;  
                background:#FFFFFF;  
                z-index:1;  
                border-radius:95px;  
           }  
           .switch:after{  
                content:' ';  
                width:88px;  
                height:88px;  
                border-radius:86px;  
                z-index:2;  
                background:#FFFFFF;  
                position:absolute;  
                transition-duration:500ms;  
                top:6px;  
                left:6px;  
                box-shadow:0 2px 5px #999999;  
           }  
           .switchOn, .switchOn:before{  
                background:#4cd964; !important;  
           }  
           .switchOn:after{  
                left:105px;   
           }  
           </style>  
           <script>  
           $(document).ready(function(){  
                $('.switch').click(function(){  
                     $(this).toggleClass("switchOn");  
                });  
           });  
           </script>  
      </head>  
      <body>  
           <div class="wrapper" align="center">  
                <br />  
                <label>  
                     <input type="checkbox" name="switch" class="checkbox" />  
                     <div class="switch"></div>  
                </label>  
                <br />  
           </div>  
      </body>  
 </html>  

Saturday, 23 April 2016

Create Simple Progress bar using css with jquery



How to create simple progress bar using css with jquery, you can learn this things in this post. In css part I have use transition effect for increase width of span tag very smoothly and In Jquery I have use setInterval() method for increase width of span tag and if width greater than 100% than at that time I have use clearInterval() method for clear the interval timer set by setInterval() method.


Online Demo




Create Simple Progress bar using css with jquery






Source Code



<!DOCTYPE html>  
<html>  
 <head>  
 <title>Webslesson Tutorial | Progress bar using CSS and Jquery</title>  
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
    <style>  
 .wrapper{  
  width:500px;  
  margin:0 auto;  
 }  
 .progress-bar{  
  width:100%;  
  background-color:#e0e0e0;  
  padding:3px;  
  border-radius:3px;  
 }  
 .progress-bar-fill{  
  height:50px;  
  display:block;  
  background-color:#33cc33;  
  border-radius:3px;  
  width:0;  
  transition: width 500ms ease-in-out;  
 }  
 </style>  
 <script>  
 $(document).ready(function(){
  $('#start').click(function(){
   var size = 0;  
   var interval = setInterval(function(){  
    size = size + 10;  
    $('.progress-bar-fill').css('width', size + '%');  
    if(size >= 100)  
    {  
     clearInterval(interval);  
    }  
   }, 1000);
  });    
 });  
 </script>  
 </head>  
 <body>  
  <div class="wrapper">  
   <br />
   <h3 align="center">Create Simple Progress bar using css with jquery</h3>
   <br />
   <div class="progress-bar">  
    <span class="progress-bar-fill"></span>  
   </div>  
   <br /><br />
   <button type="button" name="start" id="start" style="padding:8px 16px;">Start</button>
   <br /><br />
  </div>  
 </body>  
</html>