AngularJS Progress Bar With PHP/MySQLi


Getting Started

I’ve used Bootstrap and Angular JS in this tutorial, so you need an internet connection for them to work. Angular JS version = 1.5.7.

Creating a Database

First, we’re going to create our database.

1. Open phpMyAdmin.

2. Click databases, create a database and name it as angular.

3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.

CREATE 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;


angular js progressbar in php

index.php

Next, this is a index which contains our upload form and a uploaded files table.

<!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="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>  
</head>
<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">&times;</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">&times;</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>Original FileName</th>
                    <th>New FileName</th>
                    <th>Type</th>
                    <th>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>
    </div>
</div>
<script src="angular.js"></script>
</body>
</html>

angular.js

This contains a angular.js codes.

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 = "";
    }	
});

fetch.php

This is a PHP api/code that fetches a uploaded files.

<?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);
?>

upload.php

Lastly, this is a PHP code/api in uploading a files.

<?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 the 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.

That ends this tutorial. Happy Coding!

Download Code

 

 



Sharing is caring!

Facebook Comments

Leave a Reply