article

Thursday, January 20, 2022

AngularJS Upload with PHP MySQLi

AngularJS 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, '1642658228_01.jpg'),
(2, '1642668773_02.jpg'),
(3, '1642669093_14813122_10154009777823730_1000226838_o.jpg');

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

ALTER TABLE `uploads`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
index.php
//index.php
<!DOCTYPE html>
<html >
<head>
<title>AngularJS 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" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="uploadphpmysql" ng-controller="uploadcontroller" ng-init="fetch()">
<div class="container">
	<h1 class="page-header text-center">AngularJS Upload with PHP MySQLi</h1>
	<div class="row" style="margin-top:60px;">
		<div class="col-4">
			<h3 class="text-center">Upload File</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files">
			<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-8">
			<div class="row">
			<div class="col-4" ng-repeat="image in images">
				<img ng-src="upload/{{ image.file_name }}" width="100%" height="250px" class="thumbnail">
			</div>
			</div>
		</div>
	</div>
</div>
<script src="appupload.js"></script>
</body>
</html>
appupload.js
//appupload.js
var app = angular.module('uploadphpmysql', []);
app.directive('fileInput', function($parse){
	return{
		restrict: 'A', //'A' - only matches attribute name
		link:function($scope, element, attrs){
			element.on('change', function(e){
				var files = e.target.files;
				$parse(attrs.fileInput).assign($scope, element[0].files);
				$scope.$apply();
			});
		}
	}
});
app.controller('uploadcontroller', 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)){
		$newFilename = time() . "_" . $_FILES['file']['name'];
		$path = 'upload/' . $newFilename;
		if(move_uploaded_file($_FILES['file']['tmp_name'], $path)){
			$sql = "INSERT INTO uploads (file_name) VALUES ('$newFilename')";
			$query=$conn->query($sql);
			if($query){
				$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