AngularJS Upload with PHP/MySQLi

Getting Started

I've used CDN for Bootstrap and Angular JS so you need internet connection for them to work.

Creating our Database

First, we are 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.
  1. CREATE TABLE `upload` (
  2. `imageid` int(11) NOT NULL AUTO_INCREMENT,
  3. `filename` varchar(200) NOT NULL,
  4. PRIMARY KEY(`imageid`)
database sql

Creating our Output Folder

Next, we're going to create a folder which will contain our uploaded files. In the root directory of our project, create a new folder and name it as upload.

index.php

Next, we're going to create our index which contains our upload form and displays our uploaded files, in the case of this tutorial, uploaded images.
  1. <!DOCTYPE html>
  2. <html >
  3. <title>AngularJS Upload with PHP/MySQLi</title>
  4. <meta charset="utf-8">
  5. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  7. </head>
  8. <body ng-app="app" ng-controller="uploader" ng-init="fetch()">
  9. <div class="container">
  10. <h1 class="page-header text-center">AngularJS Upload with PHP/MySQLi</h1>
  11. <div class="row">
  12. <div class="col-md-3">
  13. <h3 class="text-center">Upload File</h3>
  14. <hr>
  15. <label>File:</label>
  16. <input type="file" file-input="files">
  17. <hr>
  18. <button class="btn btn-primary" ng-click="upload()"><span class="glyphicon glyphicon-download-alt"></span> Upload</button>
  19. <div ng-show="error" class="alert alert-danger text-center" style="margin-top:30px;">
  20. <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
  21. <span class="glyphicon glyphicon-remove"></span> {{ errorMessage }}
  22. </div>
  23. <div ng-show="success" class="alert alert-success text-center" style="margin-top:30px;">
  24. <button type="button" class="close" ng-click="clearMessage()"><span aria-hidden="true">&times;</span></button>
  25. <span class="glyphicon glyphicon-check"></span> {{ successMessage }}
  26. </div>
  27. </div>
  28. <div class="col-md-9">
  29. <div class="col-md-4" ng-repeat="image in images">
  30. <img ng-src="upload/{{ image.filename }}" width="100%" height="250px" class="thumbnail">
  31. </div>
  32. </div>
  33. </div>
  34. </div>
  35. <script src="angular.js"></script>
  36. </body>
  37. </html>

angular.js

This is contains our Angular JS code in fetching data from database and uploading data into our database.
  1. var app = angular.module('app', []);
  2. app.directive('fileInput', function($parse){
  3. return{
  4. restrict: 'A',
  5. link:function($scope, element, attrs){
  6. element.on('change', function(e){
  7. var files = e.target.files;
  8. $parse(attrs.fileInput).assign($scope, element[0].files);
  9. $scope.$apply();
  10. });
  11. }
  12. }
  13. });
  14. app.controller('uploader', function($scope, $http){
  15. $scope.error = false;
  16. $scope.errorMessage = "";
  17. $scope.success = false;
  18. $scope.successMessage = "";
  19. $scope.upload = function(){
  20. var uploadForm = new FormData();
  21. angular.forEach($scope.files, function(file){
  22. uploadForm.append('file', file);
  23. });
  24. $http.post('upload.php', uploadForm, {
  25. transformRequest:angular.identity,
  26. headers: {'Content-Type':undefined, 'Process-Data': false}
  27. }).success(function(response){
  28. if(response.error){
  29. $scope.error = true;
  30. $scope.errorMessage = response.message;
  31. }
  32. else{
  33. $scope.success = true;
  34. $scope.successMessage = response.message;
  35. $scope.fetch();
  36. }
  37. })
  38. },
  39.  
  40. $scope.fetch = function(){
  41. $http.get('fetch.php')
  42. .success(function(data){
  43. $scope.images = data;
  44. });
  45.  
  46. }
  47.  
  48. $scope.clearMessage = function(){
  49. $scope.error = false;
  50. $scope.errorMessage = "";
  51. $scope.success = false;
  52. $scope.successMessage = "";
  53. }
  54. });

fetch.php

This is our PHP code in fetching the uploaded files in our database.
  1. <?php
  2. $conn = new mysqli('localhost', 'root', '', 'angular');
  3. $output = array();
  4. $sql = "SELECT * FROM upload";
  5. $query=$conn->query($sql);
  6. while($row=$query->fetch_array()){
  7. $output[] = $row;
  8. }
  9.  
  10. echo json_encode($output);
  11. ?>

upload.php

Lastly, this contains our PHP code in uploading files into our database.
  1. <?php
  2.  
  3. $conn = new mysqli('localhost', 'root', '', 'angular');
  4. $out = array('error' => false);
  5. if(!empty($_FILES)){
  6. $newFilename = time() . "_" . $_FILES['file']['name'];
  7. $path = 'upload/' . $newFilename;
  8. if(move_uploaded_file($_FILES['file']['tmp_name'], $path)){
  9. $sql = "INSERT INTO upload (filename) VALUES ('$newFilename')";
  10. $query=$conn->query($sql);
  11. if($query){
  12. $out['message'] = 'File Uploaded Successfully';
  13. }
  14. else{
  15. $out['error'] = true;
  16. $out['message'] = 'File Uploaded but not Saved';
  17. }
  18. }
  19. }
  20. else{
  21. $out['error'] = true;
  22. $out['message'] = 'Upload Failed. File empty!';
  23. }
  24.  
  25. echo json_encode($out);
  26. ?>
That ends this tutorial. Happy Coding :)

Add new comment