Home AngularJs How to image upload with preview in PHP with AngularJS ?

How to image upload with preview in PHP with AngularJS ?

by Shahriar Sagor

Today now in this post i will show you How to image upload with preview in PHP with AngularJS ? Sometimes, we may need to make image uploading also with preview selected image before the upload by using AngularJS. So, now this post will be help you how to image or any file upload in AngularJS with PHP.

So In this example i will not use any plugin or directive for the image upload. It is very simple so we can use the very simple and anywhere. For the front-end code write in the AngularJS and back-end code write in PHP(for image upload code). So It will also display the preview of image before the upload.

This example is working on the bellow listed three things, we can see.



3)images(images is a directory, it should on the root path)

After this we can put the code like as bellow, so let’s see in bellow code.

<!DOCTYPE html>
  <title>Angularjs Image Uploading</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="main-App" ng-controller="AdminController">
	<!-- Form Start -->
	<form ng-submit="submit()" name="form" role="form">
	  <input ng-model="form.image" type="file" class="form-control input-lg" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)" style="width:400px" >
	  <input type="submit" id="submit" value="Submit" />
	  <img ng-src="{{image_source}}" style="width:300px;">
	<!-- Form End -->
	<script type="text/javascript">
	    var app =  angular.module('main-App',[]);
	    app.controller('AdminController', function($scope, $http) {
	      $scope.form = [];
	      $scope.files = [];
	      $scope.submit = function() {
	      	$scope.form.image = $scope.files[0];
			  method  : 'POST',
			  url     : '/upload.php',
			  processData: false,
			  transformRequest: function (data) {
			      var formData = new FormData();
			      formData.append("image", $scope.form.image);  
			      return formData;  
			  data : $scope.form,
			  headers: {
			         'Content-Type': undefined
	      $scope.uploadedFile = function(element) {
		    $scope.currentFile = element.files[0];
		    var reader = new FileReader();
		    reader.onload = function(event) {
		      $scope.image_source = event.target.result
		      $scope.$apply(function($scope) {
		        $scope.files = element.files;


		$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
                $image = time().'.'.$ext;
                move_uploaded_file($_FILES["image"]["tmp_name"], 'images/'.$image);
		echo "Image uploaded successfully as ".$image;
		echo "Image Is Empty";

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook


You may also like