Getting Started
Angular JS version = 1.5.7
.
Creating our Database
First, we’re going to create our database. “Apache” and “MySQL” Servers are required too in this tutorial. In my case I am using XAMPP as my virtual server.
- Open PHPMyAdmin.
- Click databases, create a database and name it as
angular
. - After creating a database, click the
SQL
and copy/paste the below codes. -
1234567CREATE TABLE `upload` (`uploadid` int(11) NOT NULL AUTO_INCREMENT,`original` varchar(150) NOT NULL,`new` varchar(150) NOT NULL,`type` varchar(10) NOT NULL,PRIMARY KEY(`uploadid`)) ENGINE=InnoDB DEFAULT CHARSET=latin1
Creating the Interface
Next, this is our index which contains our upload form and our uploaded files table. Create a new file and copy/paste the script below and save it as index.php
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html > <head> <title>AngularJS Progress Bar with PHP/MySQLi</title> <meta charset="utf-8"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> </head> <style> td{ word-break: break-all; } </style> <body ng-app="app" ng-controller="uploader" ng-init="fetch()"> <div class="container"> <h1 class="page-header text-center">AngularJS Progress Bar with PHP/MySQLi</h1> <div class="row"> <div class="col-md-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> <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 class="col-md-9"> <table class="table table-bordered table-striped"> <thead> <th width="25%">Original FileName</th> <th width="25%">New FileName</th> <th width="25%">Type</th> <th width="25%">File Location</th> </thead> <tbody> <tr ng-repeat="upload in uploads"> <td>{{ upload.original }}</td> <td>{{ upload.new }}</td> <td>{{ upload.type }}</td> <td>upload/{{ upload.new }}</td> </tr> </tbody> </table> <!-- <div class="col-md-4" ng-repeat="image in images"> <img ng-src="upload/{{ image.filename }}" width="100%" height="250px" class="thumbnail"> </div> --> </div> </div> </div> <script src="angular.js"></script> </body> </html> |
Creating the Script
Angular.js
codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
var app = angular.module('app', []); 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('uploader', function($scope, $http){ $scope.showProgress = false; $scope.error = false; $scope.errorMessage = ""; $scope.success = false; $scope.successMessage = ""; $scope.upload = function(){ var uploadForm = new FormData(); angular.forEach($scope.files, function(file){ uploadForm.append('file[]', file); }); $http.post('upload.php', uploadForm, { transformRequest:angular.identity, 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) + ' %'; } } } }) .success(function(response){ console.log(response); if(response.error){ $scope.error = true; $scope.errorMessage = response.message; } else{ $scope.success = true; $scope.successMessage = response.message; $scope.fetch(); } }) } $scope.fetch = function(){ $http.get('fetch.php') .success(function(data){ $scope.uploads = data; }); } $scope.clearMessage = function(){ $scope.error = false; $scope.errorMessage = ""; $scope.success = false; $scope.successMessage = ""; } }); |
Creating a Fetch API and Saving Process
PHP API/code that fetches our uploaded files.fetch.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php $conn = new mysqli('localhost', 'root', '', 'angular'); $output = array(); $sql = "SELECT * FROM upload"; $query=$conn->query($sql); while($row=$query->fetch_array()){ $output[] = $row; } echo json_encode($output); ?> |
Lastly, this is our PHP code/API in uploading our files.upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
$scope.fetch = function(){ $http.get('fetch.php') .success(function(data){ $scope.uploads = data; }); } $scope.clearMessage = function(){ $scope.error = false; $scope.errorMessage = ""; $scope.success = false; $scope.successMessage = ""; } }); Creating a Fetch API and Saving Process This is our PHP API/code that fetches our uploaded files. fetch.php <?php $conn = new mysqli('localhost', 'root', '', 'angular'); $output = array(); $sql = "SELECT * FROM upload"; $query=$conn->query($sql); while($row=$query->fetch_array()){ $output[] = $row; } echo json_encode($output); ?> Lastly, this is our PHP code/API in uploading our files. upload.php <?php $conn = new mysqli('localhost', 'root', '', 'angular'); $out = array('error' => false); if(!empty($_FILES['file']['name'])){ $count = count($_FILES['file']['name']); foreach ($_FILES['file']['name'] as $key => $filename){ $newFilename = time() . "_" . $filename; $ext = strtoupper(pathinfo($filename, PATHINFO_EXTENSION)); $path = 'upload/' . $newFilename; if(move_uploaded_file($_FILES['file']['tmp_name'][$key], $path)){ $sql = "INSERT INTO upload (original, new, type) VALUES ('$filename', '$newFilename', '$ext')"; $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); ?> |
Note: You can increase upload size of your localhost by setting the value of upload_max_filesize
and post_max_size
in your php.ini
. Then, restart your localhost server to save your changes.