article

Tuesday, January 18, 2022

AngularJS Multiple Upload with Progress Bar and PHP MySQLi

AngularJS Multiple Upload with Progress Bar and PHP MySQLi

Bootstrap 5.1 Version
https://getbootstrap.com/docs/5.1/getting-started/introduction/

angularjs CDN
https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS Upload with Progress Bar and PHP MySQLi</title>
<meta charset="utf-8">
<link rel = "stylesheet" type = "text/css" href = "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="progressbarupload" ng-controller="MainControl" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Multiple Upload with Progress Bar and PHP MySQLi</h1>
	<div class="row">
		<div class="col-md-12">
			<h3 class="text-left">Upload File/s</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files" multiple>
			<hr>
			<button class="btn btn-primary" ng-click="upload()"><span class="glyphicon glyphicon-download-alt"></span> Upload</button>
			
			<progress id="progress" max="100" value="{{progressBar}}" ng-show="showProgress" style="height:30px; width:100%; margin-top:30px;"></progress>
			<div class="text-center">{{progressCounter}}</div>
			
			<div ng-show="error" class="alert alert-danger text-center" style="margin-top:30px;">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-remove"></span> {{ errorMessage }}
			</div>
			<div ng-show="success" class="alert alert-success text-center" style="margin-top:30px;">
				<button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">×</span></button>
				<span class="glyphicon glyphicon-check"></span> {{ successMessage }}
			</div>
			
		</div>
	</div>	
	<div class="row">
		<div class="col-md-12">
			<table class="table table-bordered table-striped" style="margin-top:10px;">
				<thead>
					<th>File</th>
				</thead>
				<tbody>
					<tr ng-repeat="upload in uploads">
						<td>{{ upload.file_name }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
//script.js
var app = angular.module('progressbarupload', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
		restrict: 'A',
		link: function($scope, elm, attrs){
			elm.bind('change', function(){
				$parse(attrs.fileInput).assign($scope, elm[0].files);
				$scope.$apply();
			});
		}
	}
}]);
app.controller('MainControl', function($scope, $http){
	$scope.showProgress = false;
	$scope.error = false;
	$scope.errorMessage = "";
	$scope.success = false;
	$scope.successMessage = "";
	$scope.upload = function(){
		
		$http({
            method: 'POST',
            url: 'upload.php',
			transformRequest: function (data) { 
				var uploadForm = new FormData();
				angular.forEach($scope.files, function(file){
					uploadForm.append('file[]', file);
				});
				return uploadForm; 
            },
			headers: {'Content-Type':undefined, 'Process-Data': false},
			uploadEventHandlers: {
		        progress: function (e) {
		                  if (e.lengthComputable) {
		                  		$scope.showProgress = true;
		                     	$scope.progressBar = (e.loaded / e.total) * 100;
		                     	$scope.progressCounter = $scope.progressBar.toFixed(2) + ' %';
		                  }
		        }
		    }
        }).then(function (data){
            console.log(data)
			if(data.error){
				$scope.error = true;
				$scope.errorMessage = data.data.message;
			}
			else{
				$scope.success = true;
				$scope.successMessage = data.data.message;
				$scope.fetch();
			}
        },function (error){
            console.log(error, 'can not get data.');
        });
		
		
	}

	$scope.fetch = function(){
        $http({
            method: 'GET',
            url: 'fetch.php',
        }).then(function (data){
            console.log(data)
            $scope.uploads = data.data;      
        },function (error){
            console.log(error, 'can not get data.');
        });
	}

	$scope.clearMessage = function(){
		$scope.error = false;
		$scope.errorMessage = "";
		$scope.success = false;
		$scope.successMessage = "";
	}	
});
fetch.php
//fetch.php
<?php
	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	$output = array();
	$sql = "SELECT * FROM uploads";
	$query=$conn->query($sql);
	while($row=$query->fetch_array()){
		$output[] = $row;
	}

	echo json_encode($output);
?>
upload.php
//upload.php
<?php

	$conn = new mysqli('localhost', 'root', '', 'testingdb');
	$out = array('error' => false);

	if(!empty($_FILES['file']['name'])){
		$count = count($_FILES['file']['name']);
		foreach ($_FILES['file']['name'] as $key => $filename){
			$newFilename = time() . "_" . $filename;

			$path = 'upload/' . $newFilename;

			if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $path)){
				$sql = "INSERT INTO uploads (file_name) VALUES ('$newFilename')";
				$query=$conn->query($sql);
			}
			 	
			if($query){
				if($count > 1){
					$out['message'] = 'Files Uploaded Successfully';
				}
				else{
					$out['message'] = 'File Uploaded Successfully';
				}
				
			}
			else{
				$out['error'] = true;
				$out['message'] = 'File Uploaded but not Saved';
			}
		
		}
	}
	else{
		$out['error'] = true;
		$out['message'] = 'Upload Failed. File empty!';
	}

	echo json_encode($out);
?>

Related Post