PHP - Simple Image Upload Preview Using AngularJS

In this tutorial we will create a Simple Image Upload Preview Using AngularJS. This code will display a preview before sending the file to the database server. The uploaded image file is being process by angular directives that act as a POST request 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_preview, 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_preview");
  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 - Simple Image Upload Preview Using AngularJS</h3>
  16.                 <hr style = "border-top:1px dotted #000;"/>
  17.                 <div class="col-md-6">
  18.                         <form ng-submit="submit()" name="form" role="form">
  19.                                 <div class = "form-inline">    
  20.                                         <input ng-model="form.image" type="file" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)">
  21.                                         <br />
  22.                                         <button class = "btn btn-primary"><span class = "glyphicon glyphicon-upload"></span> Upload</button>
  23.                                 </div> 
  24.                                 <br/>
  25.                         </form>
  26.                 </div>
  27.                 <div class="col-md-6">
  28.                         <center><img ng-src="{{image_source}}" style="width:250px; height:200px;"></center>
  29.                 </div>
  30.         </div>         
  31. </body>
  32. <script src="js/angular.js"></script>
  33. <script src = "js/script.js"></script>
  34. </html>

Creating the Main Function

This code contains the main function of the application. This code will display a preview for the uploaded file before saving it. 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['image'])){
  5.                 $file_name = $_FILES['image']['name'];
  6.                 $file_temp = $_FILES['image']['tmp_name'];
  7.                
  8.                 $exp = explode(".", $file_name);
  9.                 $ext = end($exp);
  10.                 $image = time().'.'.$ext;
  11.                 $ext_allowed = array("png", "gif", "jpeg", "jpg");
  12.                 $location = "uploads/".$image;
  13.                 if(in_array($ext, $ext_allowed)){
  14.                         move_uploaded_file($file_temp, $location);
  15.                         mysqli_query($conn, "INSERT INTO `image` (image, location) VALUES('$image', '$location')") or die(mysqli_error());
  16.                         echo "Successfully uploaded!";
  17.                 }else{
  18.                         echo "Invalid image format";
  19.                 }
  20.         }else{
  21.                 echo "Please upload image first";
  22.         }
  23. ?>
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.                  
  9.                   $scope.uploadedFile = function(element) {
  10.                     $scope.currentFile = element.files[0];
  11.                     var reader = new FileReader();
  12.                     reader.onload = function(event) {
  13.                       $scope.image_source = event.target.result
  14.                       $scope.$apply(function($scope) {
  15.                         $scope.files = element.files;
  16.                       });
  17.                     }
  18.                     reader.readAsDataURL(element.files[0]);
  19.                   }
  20.                  
  21.               $scope.submit = function() {
  22.                 $scope.form.image = $scope.files[0];
  23.  
  24.                 $http({
  25.                           method  : 'POST',
  26.                           url     : 'upload.php',
  27.                           processData: false,
  28.                           transformRequest: function (data) {
  29.                               var formData = new FormData();
  30.                               formData.append("image", $scope.form.image);  
  31.                               return formData;  
  32.                           },  
  33.                           data : $scope.form,
  34.                           headers: {
  35.                                  'Content-Type': undefined
  36.                           }
  37.                    }).then(function(data){
  38.                                 alert(data.data);
  39.                    });
  40.  
  41.               };
  42.             });
There you have it we successfully created a Simple Image Upload Preview 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