How to Upload file with AngularJS and PHP

How to Upload file with AngularJS and PHP

Hello friends, in this post we are going to learn how to upload file using AngularJS and PHP

For upload file with AngularJS need to send the file by $http service and with the use PHP store the requested file to the server and return a response.

In the demonstration, I am creating two examples –

  • In the first, using JavaScript to select a file,
  • And in the second, using a custom directive

Then pass it as data in $http service for upload.

1. Without Custom directive

HTML

Create a file element, a button for upload, and <p> for display response result.

With button added ng-click directive which calls upload() function.

Completed Code

<body ng-app='myapp'>

 <div ng-controller="userCtrl">

  <input type='file' name='file' id='file'><br/>
  <input type='button' value='Upload' id='upload' ng-click='upload()' >

  <p>{{ response.name }}</p>
 </div>

</body>

AngularJS

Declare a module and define $scope.upload in the controller which trigger on the button click.

Within the function get the selected file from the file element and append it to FormData object variable fd.

Sending POST request using $http service where pass FormData object as data and set Content-Type: undefined using headers property.

Completed Code

var upload= angular.module('myapp', []);

upload.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
 $scope.upload = function(){

  var fd = new FormData();
  var files = document.getElementById('file').files[0];
  fd.append('file',files);

  // AJAX request
  $http({
   method: 'post',
   url: 'upload.php',
   data: fd,
   headers: {'Content-Type': undefined},
  }).then(function successCallback(response) { 
    // Store response data
    $scope.response = response.data;
  });
 }

}]);

2. With Custom directive

HTML

Only added a custom model ng-file='uploadfiles' on input element and other code will be same as the above example.

Completed Code

<body ng-app='myapp'>

 <div ng-controller="userCtrl">

  <input type='file' name='file' id='file' ng-file='uploadfiles'><br/>
  <input type='button' value='Upload' id='upload' ng-click='upload()' >

  <p>{{ response.name }}</p>
 </div>

</body>

AngularJS

Declaring custom directive using .directive where initializing the scope when the change event trigger and use it to define FormData Object variable fd.

Completed Code

var upload = angular.module('myapp', []);
upload.directive('ngFile', ['$parse', function ($parse) {
 return {
  restrict: 'A',
  link: function(scope, element, attrs) {
   element.bind('change', function(){

    $parse(attrs.ngFile).assign(scope,element[0].files)
    scope.$apply();
   });
  }
 };
}]);

upload.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {

 $scope.upload = function(value){
  var fd=new FormData();
  angular.forEach($scope.uploadfiles,function(file){
  fd.append('file',file);
 });

 $http({
  method: 'post',
  url: 'upload.php',
  data: fd,
  headers: {'Content-Type': undefined},
 }).then(function successCallback(response) { 
  // Store response data
  $scope.response = response.data;
 });
}

}]);

3. PHP

Create a new upload.php file and an upload directory.

Upload file to upload directory and return an Array in JSON format which has a file name.

Completed Code

<?php

/* Getting file name */
$filename = $_FILES['file']['name'];

/* Location */
$location = 'upload/';

/* Upload file */
move_uploaded_file($_FILES['file']['tmp_name'],$location.$filename);

$arr = array("name"=>$filename);
echo json_encode($arr);

4. Demo

Browse a file and click the upload button.

5. Conclusion

Both examples are same only FormData initializing step is different. You can use any of them to upload file to server with Angular.

Thank for reading, I hope this tutorial will surely help and you if you liked this tutorial, please consider sharing it with others.

This post was originally published here

angular-js php angular web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...