article

Friday, January 28, 2022

AngularJS Multiple File Upload with PHP MySQLi

AngularJS Multiple File Upload with 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

CREATE TABLE `uploads` (
  `id` int(11) NOT NULL,
  `file_name` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `uploads` (`id`, `file_name`) VALUES
(1, '1643355908_01.jpg'),
(2, '1643426291_02.jpg'),
(3, '1643426291_13532763_1267843279894447_3651828689419392719_n.jpg'),
(4, '1643426291_13882562_10153788775718730_5796830824454484119_n.jpg');

ALTER TABLE `uploads`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `uploads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS Multiple File Upload with PHP MySQLi</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-app="uploadmultiple" ng-controller="uploadCTR" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Multiple File Upload with PHP MySQLi</h1>
	<div class="row">
		<div class="col-3">
			<h3 class="text-center">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>
			<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 class="col-9">
			<div class="row">
			<div class="col-md-4" ng-repeat="rs in images" style="margin-bottom:10px;">
				<img ng-src="upload/{{ rs.file_name }}" width="100%" height="250px" class="thumbnail">
			</div>
			</div>
		</div>
	</div>
</div>
<script src="angular.js"></script>
</body>
</html>
angular.js
//angular.js
var app = angular.module('uploadmultiple', []);
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('uploadCTR', function($scope, $http){

	$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},
        }).then(function (data){
            console.log(data) 
			if(data.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.images = 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