Showing posts with label multiple. Show all posts
Showing posts with label multiple. Show all posts

Tuesday, 3 August 2021

Drag And Drop Multiple File Upload with Progress Bar using JavaScript


Hi Guys, In this tutorial, You can learn How to make Drag and Drop File Upload Feature with progress bar by using Pure Vanilla JavaScript with HTML CSS and PHP. In previous tutorial, we have already shared tutorial on how to Upload multiple file with progress bar using JavaScript with PHP by select multiple file from file tag but under this post, we will show you have can we upload multiple file by drag and drop feature with progress bar using JavaScript in PHP.

Do you know What is Drag and Drop File Upload, so if you not know then Drag and Drop file uploading means, we can directly upload file by drag and drop. By using Drag & Drop file upload feature, it has provide interfaces which will permits our web application to drag and drop files on the web page. We have seen this types of functionality on many websites on internet. So for make drag and drop features, there are many JavaScript libraries are available and by using that library we can build our own drag and drop multiple file upload feature by writing few lines of code but under this tutorial we will make drag and drop multiple file upload features by using pure JavaScript without using any in build library.


Drag And Drop Multiple File Upload with Progress Bar using JavaScript




Under this Drag and Drop Multiple File Upload tutorial, there will be a drag area on web page, so when we have drag any file over this drag area then the border of that drag area will be change to solid and it will display copy file here text under drag area. So when we have drop multiple file under this drag area, then it will start uploading file one by one and it will display multiple file upload process in progress bar.





In this tutorial, we have use HTML, CSS JavaScript and Bootstrap 5 Style sheet library at client-side that means drag area we will create using HTML and CSS, files data get from drag and drop area using JavaScript, progress bar will be create using Bootstrap and at server side we have use PHP Script for upload multiple file on to the server. Below you can find source code of Drag and Drop Upload Multiple files with progress bar using JavaScript in PHP.

Source Code


index.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 & Drop Upload Multiple File with Progress Bar using JavaScript in PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-5 mb-5 text-center text-primary"><b>Drag & Drop Upload Multiple File with Progress Bar using JavaScript in PHP</b></h1>

            <div class="card">
                <div class="card-header">Drag & Drop File Here</div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-3">&nbsp;</div>
                        <div class="col-md-6">
                            <div id="drag_drop">Drag & Drop File Here</div>
                        </div>
                        <div class="col-md-3">&nbsp;</div>
                    </div>
                </div>
            </div>
            <br />
            <div class="progress" id="progress_bar" style="display:none; height:50px;">
                <div class="progress-bar bg-success" id="progress_bar_process" role="progressbar" style="width:0%; height:50px;">0%

                </div>
            </div>
            <div id="uploaded_image" class="row mt-5"></div>
        </div>
    </body>
</html>

<style>

#drag_drop{
    background-color : #f9f9f9;
    border : #ccc 4px dashed;
    line-height : 250px;
    padding : 12px;
    font-size : 24px;
    text-align : center;
}

</style>

<script>

function _(element)
{
    return document.getElementById(element);
}

_('drag_drop').ondragover = function(event)
{
    this.style.borderColor = '#333';
    return false;
}

_('drag_drop').ondragleave = function(event)
{
    this.style.borderColor = '#ccc';
    return false;
}


_('drag_drop').ondrop = function(event)
{
    event.preventDefault();

    var form_data  = new FormData();

    var image_number = 1;

    var error = '';

    var drop_files = event.dataTransfer.files;

    for(var count = 0; count < drop_files.length; count++)
    {
        if(!['image/jpeg', 'image/png', 'video/mp4'].includes(drop_files[count].type))
        {
            error += '<div class="alert alert-danger"><b>'+image_number+'</b> Selected File must be .jpg or .png Only.</div>';
        }
        else
        {
            form_data.append("images[]", drop_files[count]);
        }

        image_number++;
    }

    if(error != '')
    {
        _('uploaded_image').innerHTML = error;
        _('drag_drop').style.borderColor = '#ccc';
    }
    else
    {
        _('progress_bar').style.display = 'block';

        var ajax_request = new XMLHttpRequest();

        ajax_request.open("post", "upload.php");

        ajax_request.upload.addEventListener('progress', function(event){

            var percent_completed = Math.round((event.loaded / event.total) * 100);

            _('progress_bar_process').style.width = percent_completed + '%';

            _('progress_bar_process').innerHTML = percent_completed + '% completed';

        });

        ajax_request.addEventListener('load', function(event){

            _('uploaded_image').innerHTML = '<div class="alert alert-success">Files Uploaded Successfully</div>';

            _('drag_drop').style.borderColor = '#ccc';

        });

        ajax_request.send(form_data);
    }
}

</script>


upload.php



<?php

//upload.php

if(isset($_FILES['images']))
{
	for($count = 0; $count < count($_FILES['images']['name']); $count++)
	{
		$extension = pathinfo($_FILES['images']['name'][$count], PATHINFO_EXTENSION);

		$new_name = uniqid() . '.' . $extension;

		move_uploaded_file($_FILES['images']['tmp_name'][$count], 'images/' . $new_name);
	}

	echo 'success';
}

?>






Friday, 30 July 2021

JavaScript Multiple File Upload Progress bar with PHP


Vanilla JavaScript Multiple File Upload with Progress bar using Ajax with PHP. In this tutorial, we will show you how to upload multiple file with progress bar using pure vanilla JavaScript with Ajax & PHP.

When we have upload file on to the server, so on web page we can not check the file uploading progress, and it is very difficult for user to check the file upload process. So at time Progress bar or progress meter is very useful feature, because it has reduce the issue of displaying multiple file upload process or progress on web page in graphical form. Because A Progress bar or Progress meter is a graphical element which has display live uploading progress on web page. So mainly Progress bar has bee used for display progress process in percentage format at the time when we have upload or download or install any software. So under this tutorial, we will show you how to upload multiple file with progress bar using JavaScript & Ajax with PHP script.

If you have made web application then under Web based application we need to upload file to server, so at that time we need to display progress bar while uploading of multiple image file in PHP. So from this tutorial, you can find the solution of how to display multiple image file upload progress in progress bar meter using JavaScript & Ajax with PHP script. Under this tutorial, we will use Pure Vanilla JavaScript for send selected multiple files to server at client-side and for upload multiple files to server, we will use PHP script at server-side.


JavaScript Multiple File Upload Progress bar with PHP






Under this tutorial, we have use following technology for Upload Multiple file with Progress bar using JavaScript with PHP.

  • HTML
  • Bootstrap 5 Stylesheet Only
  • Vanilla JavaScript
  • Ajax
  • PHP




Source Code


index.php



<!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>Multiple File Upload with Progress Bar using JavaScript & PHP</title>
    </head>
    <body>

        <div class="container">
            <h1 class="mt-3 mb-3 text-center">Multiple File Upload with Progress Bar using JavaScript & PHP</h1>

            <div class="card">
                <div class="card-header">Select File</div>
                <div class="card-body">
                    <table class="table">
                        <tr>
                            <td width="50%" align="right"><b>Select File</b></td>
                            <td width="50%">
                                <input type="file" id="select_file" multiple />
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <br />
            <div class="progress" id="progress_bar" style="display:none; ">

                <div class="progress-bar" id="progress_bar_process" role="progressbar" style="width:0%">0%</div>

            </div>

            <div id="uploaded_image" class="row mt-5"></div>
        </div>
    </body>
</html>

<script>

function _(element)
{
    return document.getElementById(element);
}

_('select_file').onchange = function(event){

    var form_data = new FormData();

    var image_number = 1;

    var error = '';

    for(var count = 0; count < _('select_file').files.length; count++)  
    {
        if(!['image/jpeg', 'image/png', 'video/mp4'].includes(_('select_file').files[count].type))
        {
            error += '<div class="alert alert-danger"><b>'+image_number+'</b> Selected File must be .jpg or .png Only.</div>';
        }
        else
        {
            form_data.append("images[]", _('select_file').files[count]);
        }

        image_number++;
    }

    if(error != '')
    {
        _('uploaded_image').innerHTML = error;

        _('select_file').value = '';
    }
    else
    {
        _('progress_bar').style.display = 'block';

        var ajax_request = new XMLHttpRequest();

        ajax_request.open("POST", "upload.php");

        ajax_request.upload.addEventListener('progress', function(event){

            var percent_completed = Math.round((event.loaded / event.total) * 100);

            _('progress_bar_process').style.width = percent_completed + '%';

            _('progress_bar_process').innerHTML = percent_completed + '% completed';

        });

        ajax_request.addEventListener('load', function(event){

            _('uploaded_image').innerHTML = '<div class="alert alert-success">Files Uploaded Successfully</div>';

            _('select_file').value = '';

        });

        ajax_request.send(form_data);
    }

};

</script>


upload.php



<?php

//upload.php

if(isset($_FILES['images']))
{
	for($count = 0; $count < count($_FILES['images']['name']); $count++)
	{
		$extension = pathinfo($_FILES['images']['name'][$count], PATHINFO_EXTENSION);

		$new_name = uniqid() . '.' . $extension;

		move_uploaded_file($_FILES['images']['tmp_name'][$count], 'images/' . $new_name);

	}

	echo 'success';
}


?>





Monday, 5 April 2021

Laravel 8 Tutorial - Join Multiple Table using Eloquent Model


In this post, we have share tutorial on How to join multiple tables using Eloquent Model in Laravel framework and then after fetch data from multiple table and display on web page in HTML table format. So in this post you will find the solution of how to fetch data from multiple table by join multiple table using Eloquent Model under this Laravel framework. In this post we will use inner join for fetch data data from multiple table using Eloquent join table relationship. So by using this tutorial, you can learn How to retrieve data from multiple tables using join multiple table with eloquent model relationship in single query run under this Laravel 8 framework.

So If you want to learn How to Join Multiple Tables in Laravel framework using Eloquent Model relationship then this post will help you, because in this post you can find step by step guide for implement how can we implement inner join for multiple tables join using Eloquent model under this Laravel framework. Under this post we have use Eloquent model in place of simple Laravel join, this is because Laravel Eloquent model is more effective that simple Laravel join while we have to fetch data from multiple table in single query. So for this here we have use Eloquent model for join multiple table in Laravel framework. Below you can find step by step guide for how to join multiple table using Laravel eloquent model.


Laravel 8 Tutorial - Join Multiple Table using Eloquent Model

  • Download Laravel Framework
  • Make Database connection
  • Create Model Class
  • Create Controller Class
  • Create View Blade file
  • Set Route
  • Run Laravel Server

Download Laravel Framework


For download fresh copy of Laravel framework, so first we have to into command prompt and run following command. This command will make join_table directory and under that directory it will download Laravel framework latest version.


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


Make Database connection


After download and install Laravel framework and after this we want to make first database connection. So for make database connection, we have to open .env file and under this file, we have to define mysql database configuration. So it will create database connection in Laravel framework.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Once you have make database connection, then after we have to make table in mysql database. So for this you have to run following sql script in your local database, so it will create table in your define mysql database.


--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

-- --------------------------------------------------------

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

-- --------------------------------------------------------

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

--
-- AUTO_INCREMENT for table `country`
--
ALTER TABLE `country`
  MODIFY `country_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;





Create Model Class


In Laravel framework, we have to create model class for database related operation. So for create model classe using compost, we have go to command prompt and run following command, this command will make model class file with name Country.php under app/Models folder.


php artisan make:model Country


After create model class, we have to open that file and under that file we have to define mysql table name details and column details.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;

    protected $table = 'country';

    protected $fillable = [
    	'country_name'
    ];
}



Create Controller Class


Under this Laravel framework, for handle HTTP request we have to create controller class. So for create controller using compost, we have go to command prompt and run following command.


php artisan make:controller JointableController


Once your controller class has been create then for open that file, we have go to app/Http/Controllers/JointableController.php file and under this file you have write following code for join multiple table using eloquent model and fetch data from multiple table in single query execution.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Country;

class JointableController extends Controller
{
    function index()
    {
    	$data = Country::join('state', 'state.country_id', '=', 'country.country_id')
              		->join('city', 'city.state_id', '=', 'state.state_id')
              		->get(['country.country_name', 'state.state_name', 'city.city_name']);

       	/*Above code will produce following query

        Select 
        	`country`.`country_name`, 
        	`state`.`state_name`, 
        	`city`.`city_name` 
        from `country` 
        inner join `state` 
        	on `state`.`country_id` = `country`.`country_id` 
        inner join `city` 
        	on `city`.`state_id` = `state`.`state_id`

        */

        return view('join_table', compact('data'));
    }
}

?>


Create View Blade file


For display HTML output in browser, so we have to create view blade file in Laravel framework. In Laravel framework view blade file has been store under resources/views folder. Under this file, we have create join_table.blade.php file. Under this file, it will received data from controller class file. You can find source code of this view blade file in below.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Join Table in Laravel 8 using Eloquent Model</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">How to Join Multiple Table in Laravel 8 using Eloquent Model</h1>
            <br />
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Country</th>
                            <th>State</th>
                            <th>City</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data as $row)
                            <tr>
                                <td>{{ $row->country_name }}</td>
                                <td>{{ $row->state_name }}</td>
                                <td>{{ $row->city_name }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </body>
</html>


Set Route


Under this Laravel framework, we have to set route of the controller method. For set route in Laravel 8 framework, we have to open routes/web.php file. In Laravel 8 framework for set route, we have to first import our controller class under this web.php file. And for set route you can find source code below.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\JointableController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('join_table', [JointableController::class, 'index']);



Run Laravel Server


After follow all above steps now all are set now we want to run Laravel application in browser. So for this, we have to go command prompt and run following command.


php artisan serve


Once you have run above command so after run this command it will provide us base url of our Laravel application. So for check above script output, we have to hit following url in browser.


http://127.0.0.1/join_table


Sunday, 21 April 2019

How to Join Multiple Table in Laravel 5.8



This is one more tutorial on Laravel 5.8 framework and in this post you can find how to join multiple table in Laravel 5.8 framework. Here we will take example of fetch data from two or more table by using inner join in Laravel 5.8 and display on web page. If you are looking for learn how to make inner join with multiple table in Laravel 5.8 then this tutorial will help you because here we have take simple example for fetch data from multiple table from scratch.

Join Table means returns the records or rows which are present in both table, for this there is at least one table column match between two table. So, this type of join we have to make in Laravel 5.8 framework. There is major benefits of join of multiple table is that in one query execution you can fetch data from multiple table. Below you can find source of Laravel 5.8 join multiple table by using inner join.







JoinTableController.php


app/Http/Controllers/>JoinTableController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class JoinTableController extends Controller
{
    function index()
    {
     $data = DB::table('city')
       ->join('state', 'state.state_id', '=', 'city.state_id')
       ->join('country', 'country.country_id', '=', 'state.country_id')
       ->select('country.country_name', 'state.state_name', 'city.city_name')
       ->get();
     return view('join_table', compact('data'));
    }
}
?>


join_table.blade.php


resources/views/join_table.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Join Multiple Table</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>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - Join Multiple Table</h3>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
           <thead>
            <tr>
                <th>Country</th>
                <th>State</th>
                <th>City</th>
            </tr>
           </thead>
           <tbody>
           @foreach($data as $row)
            <tr>
             <td>{{ $row->country_name }}</td>
             <td>{{ $row->state_name }}</td>
             <td>{{ $row->city_name }}</td>
            </tr>
           @endforeach
           </tbody>
       </table>
   </div>
  </div>
 </body>
</html>


web.php


routes/web.php

Route::get('join-table', 'JoinTableController@index');