Uploading an Image File using AngularJS and PHP Tutorial

In this tutorial, you will learn how to Upload an Image File using AngularJS and PHP. The tutorial aims to provide IT/CS Students and new programmers with a reference for learning to upload files using the AngularJS and PHP Language. Here, snippets that explain how to do it are provided. A sample web application that demonstrates the tutorial's objectives source code zip file is also provided and is free to download.

How to Upload an Image File using AngularJS?

Image File Uploading using AngularJS and PHP is not that complicated to achieve. Using the angular directive, we can assign the input file value into the angular $scope. Then, the PHP move_uploaded_file() function will process the uploading of the file into a directory. See the sample snippets below.

Assuming that we have the following file input form.

  1. <div class="container" ng-app="SampleApp" ng-controller="uploadController">
  2. <form action="" ng-submit="uploadImg($event)">
  3. <input class="form-control form-control-sm" id="image_file" type="file" file-input accept="image/*" required>
  4. </form>
  5. </div>

AngularJS

Here's the sample snippet of an AngularJS that handles the file input form data.

  1. var mymodule = angular.module("SampleApp",[]);
  2. mymodule.directive("fileInput", function($parse){
  3. return{
  4. link: function($scope, element, attrs){
  5. element.on("change", function(event){
  6.  
  7. var files = event.target.files;
  8. $parse(attrs.id).assign($scope, element[0].files)
  9. $scope.$apply();
  10. });
  11. }
  12. }
  13. })
  14.  
  15. mymodule.controller("uploadController", function ($scope, $http){
  16. $scope.uploadImg = function(e){
  17. e.preventDefault()
  18. var fdata = new FormData()
  19. angular.forEach($scope.image_file, function(file){
  20. fdata.append('image_file', file);
  21. });
  22. $http.post('uploadAPI.php', fdata, {
  23. transformRequest: angular.identity,
  24. headers: {'Content-Type': undefined,'Process-Data': false }
  25. }).then(
  26. function success(response){
  27.  
  28. if(response.status == 200){
  29. var data = response.data
  30. if(data.status == 'success' ){
  31. //Upload is successful
  32. }else{
  33. //Upload is unsuccesful
  34.  
  35. }
  36. e.target.reset()
  37. $scope.getImages();
  38. }
  39. }, function error(error){
  40. console.error(error)
  41. }
  42. )
  43. }
  44.  
  45. })
  46.  

PHP API

Here's the PHP Script that uploads the image file into the server's upload directory.

  1. <?php
  2. if(isset($_FILES) && !empty($_FILES['image_file']['tmp_name'])){
  3. $file = $_FILES['image_file'];
  4. $file_path_part = pathinfo($file['name']);
  5. $filename = $file_path_part['filename'];
  6. $extension = $file_path_part['extension'];
  7.  
  8. // Upload Directory
  9. $dir = 'uploads/';
  10. if(!is_dir($dir))
  11. mkdir($dir);
  12.  
  13. // Iteration starting Value
  14. $i = 0;
  15.  
  16. while(true){
  17. // Filename additional text
  18. $additional_txt = ($i>0) ? " ({$i})" : "";
  19.  
  20. // Temporary new filename
  21. $tempname = $filename.$additional_txt.".".$extension;
  22.  
  23. // Cheching Filename Duplicate
  24. if(is_file($dir.$tempname)){
  25. // If has duplicate
  26. $i++;
  27. }else{
  28. // Renew Filename
  29. $filename = $tempname;
  30. // break the loop
  31. break;
  32. }
  33. }
  34.  
  35. $upload = move_uploaded_file($file['tmp_name'], $dir.$filename);
  36. if($upload){
  37. echo json_encode(['status' => 'success']);
  38. }else{
  39. echo json_encode(['status' => 'failed', 'error' => 'Failed to upload image.']);
  40. }
  41. }else{
  42. echo json_encode(['status' => 'failed', 'error' => 'Request dont have an Image File.']);
  43. }

Example

To have a better idea of how to implement the sample snippet that I provided above, check out the sample web application snippets below. The snippets result will be a simple web application with an upload form and upload images list.

Interface

index.php

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Angular JS Upload Image</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.js" integrity="sha512-klc+qN5PPscoGxSzFpetVsCr9sryi2e2vHwZKq43FdFyhSAa7vAqog/Ifl8tzg/8mBZiG2MAKhyjH5oPJp65EA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12. html, body{
  13. min-height:100%;
  14. width:100%;
  15. }
  16. tbody:empty:after{
  17. content:'No records found'
  18. }
  19. </style>
  20. </head>
  21. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  22. <div class="container">
  23. <a class="navbar-brand" href="./">Angular JS Upload Image</a>
  24. <div>
  25. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  26. </div>
  27. </div>
  28. </nav>
  29. <div class="container-fluid px-5 my-3" ng-app="SampleApp" ng-controller="uploadController">
  30. <div class="col-lg-8 col-md-10 col-sm-12 mx-auto mb-3">
  31. <div class="card rounded-0 shadow mb-3">
  32. <div class="card-header">
  33. <div class="card-title"><b>Uploading Image using AngularJS and PHP</b></div>
  34. </div>
  35. <div class="card-body">
  36. <div class="container-fluid">
  37. <div class="alert alert-danger mb-3 rounded-0" ng-show="error">{{error_msg}}</div>
  38. <div class="alert alert-success mb-3 rounded-0" ng-show="success">{{success_msg}}</div>
  39.  
  40. <form id="uploadForm" action="" ng-submit="uploadImg($event)">
  41. <div class="mb-3">
  42. <p class="text-muted">Browse the image you want to upload here</p>
  43. </div>
  44.  
  45. <div class="mb-3">
  46. <label for="image_file" class="form-label">Browse Image</label>
  47. <input class="form-control form-control-sm" id="image_file" type="file" file-input accept="image/*" required>
  48. </div>
  49. </form>
  50. </div>
  51. </div>
  52. <div class="card-footer py-1">
  53. <div class="text-center">
  54. <button form="uploadForm" class="btn btn-primary rounded-pill col-lg-4 col-md-6 col-sm-8">Upload Image</button>
  55. </div>
  56. </div>
  57. </div>
  58. </div>
  59.  
  60. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  61. <div class="card rounded-0 shadow mb-3">
  62. <div class="card-header">
  63. <div class="card-title"><b>Uploaded Images</b></div>
  64. </div>
  65. <div class="card-body">
  66. <div class="container-fluid">
  67. <div class="list-group">
  68. <a href="{{file.path}}" ng-repeat="file in files" class="list-group-item list-group-item-action" target="_blank">
  69. {{file.name}}
  70. </a>
  71. </div>
  72. </div>
  73. </div>
  74. </div>
  75. </div>
  76. </div>
  77. <script src="app.js"></script>
  78. </body>
  79. </html>

AngularJS

app.js

  1. var mymodule = angular.module("SampleApp",[]);
  2.  
  3. /**
  4.   * Angular Controller
  5.   */
  6.  
  7. mymodule.directive("fileInput", function($parse){
  8. return{
  9. link: function($scope, element, attrs){
  10. element.on("change", function(event){
  11. $scope.error = false
  12. $scope.error_msg = ''
  13. $scope.success = false
  14. $scope.success_msg = ''
  15. var files = event.target.files;
  16. $parse(attrs.id).assign($scope, element[0].files)
  17. $scope.$apply();
  18.  
  19. });
  20. }
  21. }
  22. })
  23.  
  24.  
  25. var upload_ctrler = mymodule.controller("uploadController", function ($scope, $http){
  26. $scope.error = false
  27. $scope.error_msg = ''
  28. $scope.success = false
  29. $scope.success_msg = ''
  30. $scope.files = {}
  31.  
  32.  
  33.  
  34. /**
  35.   * Trigger Upload Image
  36.   * @param {int} page
  37.   */
  38. $scope.uploadImg = function(e){
  39. e.preventDefault()
  40. $scope.error = false
  41. $scope.error_msg = ''
  42. $scope.success = false
  43. $scope.success_msg = ''
  44. var fdata = new FormData()
  45. angular.forEach($scope.image_file, function(file){
  46. fdata.append('image_file', file);
  47. });
  48. $http.post('upload_img.php', fdata, {
  49. transformRequest: angular.identity,
  50. headers: {'Content-Type': undefined,'Process-Data': false }
  51. }).then(
  52. function success(response){
  53.  
  54. if(response.status == 200){
  55. var data = response.data
  56. if(data.status == 'success' ){
  57. $scope.success = true;
  58. $scope.success_msg = 'Image has been uploaded successfully';
  59. }else{
  60. $scope.error = true;
  61. if(!!data.error){
  62. $scope.error_msg = data.error;
  63. }else{
  64. $scope.error_msg = "Failed to upload image due to some errors.";
  65. }
  66. }
  67. e.target.reset()
  68. $scope.getImages();
  69. }
  70. }, function error(error){
  71. console.error(error)
  72. }
  73. )
  74. }
  75.  
  76.  
  77. $scope.getImages = function(){
  78. $http({
  79. method:'GET',
  80. url:"getImages.php"
  81. }).then(
  82. function success(response){
  83. if(response.status == 200){
  84. $scope.files = response.data
  85. }
  86. }, function error(error){
  87. console.error(error)
  88. }
  89. )
  90. }
  91.  
  92. $scope.getImages();
  93.  
  94.  
  95. })
  96.  
  97.  

PHP API

upload_img.php

  1. <?php
  2. if(isset($_FILES) && !empty($_FILES['image_file']['tmp_name'])){
  3. $file = $_FILES['image_file'];
  4. $file_path_part = pathinfo($file['name']);
  5. $filename = $file_path_part['filename'];
  6. $extension = $file_path_part['extension'];
  7.  
  8. // Upload Directory
  9. $dir = 'uploads/';
  10. if(!is_dir($dir))
  11. mkdir($dir);
  12.  
  13. // Iteration starting Value
  14. $i = 0;
  15.  
  16. while(true){
  17. // Filename additional text
  18. $additional_txt = ($i>0) ? " ({$i})" : "";
  19.  
  20. // Temporary new filename
  21. $tempname = $filename.$additional_txt.".".$extension;
  22.  
  23. // Cheching Filename Duplicate
  24. if(is_file($dir.$tempname)){
  25. // If has duplicate
  26. $i++;
  27. }else{
  28. // Renew Filename
  29. $filename = $tempname;
  30. // break the loop
  31. break;
  32. }
  33. }
  34.  
  35. $upload = move_uploaded_file($file['tmp_name'], $dir.$filename);
  36. if($upload){
  37. echo json_encode(['status' => 'success']);
  38. }else{
  39. echo json_encode(['status' => 'failed', 'error' => 'Failed to upload image.']);
  40. }
  41. }else{
  42. echo json_encode(['status' => 'failed', 'error' => 'Request dont have an Image File.']);
  43. }

There you go. You can now test the snippet result on your end and see if it achieves the main objective of this tutorial. I also provided the complete source code zip file on this article. You can download it by clicking the download button below.

Snapshots

Here are some snapshots of the result of the example web application.

Form Interface

Upload Image using PHP and AngularJS

Uploaded Images List

Upload Image using PHP and AngularJS

Overall Page Interface

Upload Image using PHP and AngularJS

That's it! That's the end of this tutorial. I hope this Image File Uploading using PHP and AngularJS Tutorial helps you with what you are looking for and that you'll find this tutorial useful also to your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment