AngularJS PHP – upload and display image using FileReader with example

AngularJS PHP – upload and display image using FileReader with example

In this post we will give you information about AngularJS PHP – upload and display image using FileReader with example. Hear we will give you detail about AngularJS PHP – upload and display image using FileReader with exampleAnd how to use it also give you demo for it if it is necessary.

AngularJS PHP – upload and display image using FileReader with example

In this post, i am going to tell you how to upload image with preview selected image to make sure you are going to upload valid images using AngularJS and PHP.

Here in this example, you will learn how to create your own custom service for common functionality to reuse code in your controller.

I here use simple HTML for input controls and use AngularJS for posting file data on server using $http service that is a core service of AngularJS for providing facility to communicate with the remote HTTP servers.

This is very simple example to upload any images over servers and you can easily implement this code in your application.

To handle form data on server, i create a PHP file for moving files into a directory.

So you will have to create a images directory on root first and then create two files : index.html and upload.php


index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>AngularJS PHP- upload and display image using FileReader with example</title>
  5. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  6. <body>
  7. </head>
  8. <body ng-app="myApp" ng-controller="ImageController">
  9.     <input type="file" ng-model="myFile"class="form-control" accept="image/*"onchange="angular.element(this).scope().uploadedFile(this)">
  10.     <button ng-click ="uploadFile()">upload me</button>
  11.     <br/>
  12.     <img ng-src="{{src}}">
  13. <script type="text/javascript">
  14.      var app = angular.module('myApp',[]);
  15.      // Here we write a custom service for upload file to reuse it in the controller
  16.         app.service('uploadFile',['$http',function($http){
  17.          this.uploadFiletoServer =function(file, uploadUrl){
  18.          var fd =newFormData();
  19.          fd.append('file', file);
  20.          $http.post(uploadUrl, fd,{
  21.          transformRequest: angular.identity,
  22.          headers:{'Content-Type':undefined,'Process-Data':false}
  23.          })
  24.          .success(function(data){
  25.          alert(data);
  26.          })
  27.          .error(function(){
  28.          alert("Error");
  29.          });
  30.          }
  31.          }]);
  32. app.controller('ImageController',['$scope','uploadFile',function($scope, uploadFile){
  33.      $scope.uploadFile =function(){
  34.          $scope.myFile = $scope.files[];
  35.             var file = $scope.myFile;
  36.      var url ="upload.php";
  37.      uploadFile.uploadFiletoServer(file, url);
  38.      };
  39.      $scope.uploadedFile =function(element){
  40.          var reader =newFileReader();
  41.          reader.onload=function(event){
  42.          $scope.$apply(function($scope){
  43.          $scope.files = element.files;
  44.              $scope.src = event.target.result
  45.          });
  46.          }
  47. reader.readAsDataURL(element.files[]);
  48.          }
  49.     }]);
  50. </script>
  51. </body>
  52. </html>
<!DOCTYPE html>
<html>
<head>
  <title>AngularJS PHP- upload and display image using FileReader with example</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
</head>
<body ng-app="myApp" ng-controller="ImageController">
	<input type="file" ng-model="myFile"  accept="image/*"  onchange="angular.element(this).scope().uploadedFile(this)">
	<button ng-click = "uploadFile()">upload me</button>
	<br/>
	<img ng-src="http://tridentsportscars.com/?big={{src}}">

 <script type="text/javascript">

	    var app =  angular.module('myApp',[]);

	    // Here we write a custom service for upload file to reuse it in the controller
		app.service('uploadFile', ['$http', function ($http) {
		    this.uploadFiletoServer = function(file, uploadUrl){
		         var fd = new FormData();
		         fd.append('file', file);
		         $http.post(uploadUrl, fd, {
		             transformRequest: angular.identity,
		             headers: {'Content-Type': undefined,'Process-Data': false}
		         })
		         .success(function(data){
		            alert(data);
		         })
		         .error(function(){
		            alert("Error");
		         });
		     }
		 }]);


    app.controller('ImageController',  ['$scope', 'uploadFile', function($scope, uploadFile){

	      $scope.uploadFile = function() {
	      	$scope.myFile = $scope.files[0];
 			var file = $scope.myFile; 
	        var url = "upload.php";
	        uploadFile.uploadFiletoServer(file, url);

	      };

	 $scope.uploadedFile = function(element) {
		    var reader = new FileReader();
		    reader.onload = function(event) {
		     $scope.$apply(function($scope) {
		        $scope.files = element.files;
		     	$scope.src = event.target.result  
		     });
		    }
            reader.readAsDataURL(element.files[0]);
		  }

	}]);
 </script>

</body>
</html>

In above code, you will see i create a service uploadFile and where i need it then i will inject this service in that controller.


upload.php

  1. <?php
  2.     if(!empty($_FILES['file'])){
  3.         $ext=pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
  4. $image=time().'.'.$ext;
  5. move_uploaded_file($_FILES["file"]["tmp_name"],'images/'.$image);
  6.         echo$image." successfully uploaded";
  7.     }else{
  8.         echo"Invalid File or Empty File";
  9.     }
  10. ?>
<?php
	if(!empty($_FILES['file'])){
		$ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
                $image = time().'.'.$ext;
                move_uploaded_file($_FILES["file"]["tmp_name"], 'images/'.$image);
		echo $image." successfully uploaded";
	}else{
		echo "Invalid File or Empty File";
	}
?>

Click here to know how to submit a form in AngularJS

Hope this code and post will helped you for implement AngularJS PHP – upload and display image using FileReader with example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

2  +  6  =  

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US