PHP - Form File Upload Using AngularJS

In this tutorial we will create a Form File Upload Using AngularJS. This code will upload a file to the database server when user submit the form inputs. The code use angular directives to upload file that will be process and send a POST request that will store the file to the database server using MySQLi INSERT query. This a user-friendly program feel free to modify and use it to your system. We will be using AngularJS as a framework which has additional custom HTML attributes embedded into it. It can interprets those attributes as directives to bind inputted parts of the page to a model that represent as a standard JavaScript variables.

Getting Started:

First you have to download & install XAMPP or any local server that run PHP scripts. Here's the link for XAMPP server https://www.apachefriends.org/index.html. And this is the link for the bootstrap that i used for the layout design https://getbootstrap.com/. Lastly, this is the link for the AngularJS https://angularjs.org/.

Creating Database

Open your database web server then create a database name in it db_file_angular, after that click Import then locate the database file inside the folder of the application then click ok. tut1

Creating the database connection

Open your any kind of text editor(notepad++, etc..). Then just copy/paste the code below then name it conn.php.
  1. <?php
  2.         $conn = mysqli_connect("localhost", "root", "", "db_file_angular");
  3.        
  4.         if(!$conn){
  5.                 die("Error: Failed to connect to database!");
  6.         }
  7. ?>

Creating The Interface

This is where we will create a simple form for our application. To create the forms simply copy and write it into you text editor, then save it index.php.
  1. <!DOCTYPE html>
  2. <html ng-app="myModule" >
  3.         <head>
  4.                 <meta charset = "UTF-8" name = "viewport" content = "width=device-width, initial-scale=1"/>
  5.                 <link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css"/>
  6.         </head>
  7. <body ng-controller="myController">
  8.         <nav class = "navbar navbar-default">
  9.                 <div class = "container-fluid">
  10.                         <a class = "navbar-brand" href = "https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class = "col-md-3"></div>
  14.         <div class = "col-md-6 well">
  15.                 <h3 class = "text-primary">PHP - Form File Upload Using AngularJS</h3>
  16.                 <hr style = "border-top:1px dotted #000;"/>
  17.                 <div class="col-md-4">
  18.                         <form ng-submit="submit()" name="form" role="form">
  19.                                 <div class = "form-group">     
  20.                                         <input ng-model="file" class="form-controller" type="file" class="form-control" onchange="angular.element(this).scope().uploadedFile(this)">
  21.                                 </div> 
  22.                                 <center><button class = "btn btn-primary"><span class = "glyphicon glyphicon-upload"></span> Upload</button></center>
  23.                         </form>
  24.                 </div>
  25.                 <div class="col-md-8">
  26.                         <table class="table table-bordered">
  27.                                 <thead class="alert-info">
  28.                                         <tr>
  29.                                                 <th>File Name</th>
  30.                                                 <th>File Location</th>
  31.                                         </tr>
  32.                                 <thead>
  33.                                 <tbody>
  34.                                         <?php
  35.                                                 require 'conn.php';
  36.                                                 $query=mysqli_query($conn, "SELECT * FROM `file`") or die(mysqli_error());
  37.                                                 while($fetch=mysqli_fetch_array($query)){
  38.                                                         echo"<tr>
  39.                                                                 <td>".$fetch['filename']."</td>
  40.                                                                 <td>".$fetch['location']."</td>
  41.                                                         </tr>";
  42.                                                 }
  43.                                                
  44.                                         ?>
  45.                                 </tbody>
  46.                         </table>
  47.                 </div>
  48.         </div>         
  49. </body>
  50. <script src="js/angular.js"></script>
  51. <script src = "js/script.js"></script>
  52. </html>

Creating the Main Function

This code contains the main function of the application. This code will upload a file to the database server when the button is clicked. To do this just copy and write these block of codes as shown below inside the text editor and save it as shown below. upload.php
  1. <?php
  2.         require_once 'conn.php';
  3.        
  4.         if(!empty($_FILES['file'])){
  5.                 $file_name = $_FILES['file']['name'];
  6.                 $file_temp = $_FILES['file']['tmp_name'];
  7.                 $file_size = $_FILES['file']['size'];
  8.                
  9.                 $exp = explode(".", $file_name);
  10.                 $ext = end($exp);
  11.                 $file = time().'.'.$ext;
  12.                 $location = "uploads/".$file;
  13.        
  14.                 if($file_size < 5242880){
  15.                         move_uploaded_file($file_temp, $location);
  16.                         mysqli_query($conn, "INSERT INTO `file` VALUES('', '$file', '$location')") or die(mysqli_error());
  17.                         echo "Successfully uploaded!";
  18.                 }else{
  19.                         echo "File too large too upload!";
  20.                 }
  21.         }else{
  22.                 echo "Please upload file first!";
  23.         }
  24. ?>
script.js Note: Make sure you save this file inside the js directory in order the script works.
  1. var app =  angular.module('myModule',[]);
  2.  
  3. app.controller('myController', function($scope, $http) {
  4.  
  5.         $scope.form = [];
  6.         $scope.files = [];
  7.  
  8.         $scope.uploadedFile = function(element) {
  9.                 $scope.currentFile = element.files[0];
  10.                         var reader = new FileReader();
  11.                     reader.onload = function(event) {
  12.                                 $scope.$apply(function($scope) {
  13.                                         $scope.files = element.files;
  14.                                 });
  15.                         }
  16.                 reader.readAsDataURL(element.files[0]);
  17.         }
  18.                  
  19.         $scope.submit = function() {
  20.                 $scope.form.file = $scope.files[0];
  21.            
  22.                 $http({
  23.                         method  : 'POST',
  24.                         url     : 'upload.php',
  25.                         processData: false,
  26.                         transformRequest: function (data) {
  27.                                 var formData = new FormData();
  28.                             formData.append("file", $scope.form.file);  
  29.                             return formData;  
  30.                         },  
  31.                        
  32.                         data : $scope.form,
  33.                         headers: {
  34.                                 'Content-Type': undefined
  35.                         }
  36.                 }).then(function(data){
  37.                         alert(data.data);
  38.                         window.location="index.php";
  39.                 });
  40.         };
  41. });
There you have it we successfully created a Form File Upload using AngularJS. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!

Add new comment