Showing posts with label multiple file upload. Show all posts
Showing posts with label multiple file upload. 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>
	

Tuesday, 2 July 2019

How to Upload Multiple Images with Progress Bar in Laravel 5.8



Laravel framework is a widely used PHP framework by Web developer for their web application development, and Laravel 5.8 is latest version of this framework. If you are fresher in Laravel framework, and if you are not know how to upload multiple images in Laravel 5.8 framework with display uploading process in Progress bar, then this post will help you to learn uploading multiple images with progress bar in Laravel 5.8 by using Ajax jQuery. So, User can upload multiple images on server without refresh of web page.

In Web Application file uploading is a very userful feature, because by this feature user can upload their images or file on web server from their local computer. But sometime if there is image or multimedia file size is very large and it has take some time for upload to server, then at that time how to can user can know file uploading is running or now. At that time if we have use progress bar for display uploading process on web page then user can know image uploading process is still running. For this purpose we have use progress bar for display uploading process then this feature will add our web application usability.

So, here we have make multiple image upload feature in Laravel 5.8 framework by using Ajax with jQuery. So, if User has upload multiple number of images on server folder then at that time we want to display uploading process of multiple image by using progress bar. So, in this post, we will learn how can we upload multiple image file through Laravel 5.8 with Ajax jQuery and display uploaded image file on web page.

  • Install Laravel 5.8 Application

  • Create Controller

  • Create View Blade File

  • Set Route of Controller Method

  • Run Laravel Application






Install Laravel 5.8 Application


First we need to install Laravel 5.8 application in our computer. For this we have to go Command prompt and write following command.


composer create-project --prefer-dist laravel/laravel folder_name


This command will download and install latest version of Laravel framework in define folder name.

Create Controller


Once Laravel 5.8 framework has been download and install in define folder, now we need to create controller for handle http request for multiple images. For this also we have go to command prompt and write following command.


php artisan make:controller MultipleUploadController


This above command will make MultipleUploadController.php controller file in app/Http/Controllers folder. This controller file we have make following method for make feature like upload multiple images.

index() - This is the root method of this controller. This method has load multiple_file_upload.php view file in browser.

upload() - This method has been received Ajax request for upload multiple images into define destination. This method has upload multiple images one by one. Before upload images it has rename image name and then upload into folder. After completing uploading process then it will send data to Ajax request in json format.

app/Http/Controllers/MultipleUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MultipleUploadController extends Controller
{
    function index()
    {
     return view('multiple_file_upload');
    }

    function upload(Request $request)
    {
     $image_code = '';
     $images = $request->file('file');
     foreach($images as $image)
     {
      $new_name = rand() . '.' . $image->getClientOriginalExtension();
      $image->move(public_path('images'), $new_name);
      $image_code .= '<div class="col-md-3" style="margin-bottom:24px;"><img src="/images/'.$new_name.'" class="img-thumbnail" /></div>';
     }

     $output = array(
      'success'  => 'Images uploaded successfully',
      'image'   => $image_code
     );

     return response()->json($output);
    }
}



Create View Blade File


For display output in browser, In Laravel we need to use View file. In Laravel 5.8 view file has been store in resources/views folder. In this folder we have create multiple_file_upload.blade.php file. In this file we have use jQuery, Bootstrap and jQuery Form library. In this file we have make one form for upload multiple image. For validate images in file tag, we have use accept="image/*" attribute and for select multiple images, we have use multiple attribute.

For submit form data to controller method, we have use jQuery Form plugin. So, form will be submitted without refresh of web page. Once images has been successfully uploaded then Ajax request will received uploaded images code for display on web page. Below you can find source for this view file.

resources/views/multiple_file_upload.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Multiple File Upload with Progressbar using Ajax jQuery</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>
        <script src="http://malsup.github.com/jquery.form.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Multiple File Upload with Progressbar using Ajax jQuery</h3>
     <br />
     <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">Upload Multiple Images in Laravel 5.8</h3>
                </div>
                <div class="panel-body">
                    <br />
                    <form method="post" action="{{ route('upload') }}" enctype="multipart/form-data">
                        @csrf
                        <div class="row">
                            <div class="col-md-3" align="right"><h4>Select Images</h4></div>
                            <div class="col-md-6">
                                <input type="file" name="file[]" id="file" accept="image/*" multiple />
                            </div>
                            <div class="col-md-3">
                                <input type="submit" name="upload" value="Upload" class="btn btn-success" />
                            </div>
                        </div>
                    </form>
                    <br />
                    <div class="progress">
                        <div class="progress-bar" aria-valuenow="" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                            0%
                        </div>
                    </div>
                    <br />
                    <div id="success" class="row">

                    </div>
                    <br />
                </div>
            </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
    $('form').ajaxForm({
        beforeSend:function(){
            $('#success').empty();
            $('.progress-bar').text('0%');
            $('.progress-bar').css('width', '0%');
        },
        uploadProgress:function(event, position, total, percentComplete){
            $('.progress-bar').text(percentComplete + '0%');
            $('.progress-bar').css('width', percentComplete + '0%');
        },
        success:function(data)
        {
            if(data.success)
            {
                $('#success').html('<div class="text-success text-center"><b>'+data.success+'</b></div><br /><br />');
                $('#success').append(data.image);
                $('.progress-bar').text('Uploaded');
                $('.progress-bar').css('width', '100%');
            }
        }
    });
});
</script>


Set Route of Controller Method


After creating controller and view blade file, now we have to set route for controller method. For this we have to open routes/web.php file and write following code for set route.

routes/web.php

Route::get('multiple-file-upload', 'MultipleUploadController@index');

Route::post('multiple-file-upload/upload', 'MultipleUploadController@upload')->name('upload');


Run Laravel Application


Once all code is ready, so lastly we need to start Laravel server, for that we have to go command prompt and write following command.


php artisan serve


This command will start Laravel application. For run this upload multiple image feature, we have to write http://127.0.0.1:8000/multiple-file-upload in browser tab, then you can access this Laravel 5.8 multiple image upload with progress bar on web page. Let's check it is working or not. Happy Laravel coding.