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.
AngularJS
Here's the sample snippet of an AngularJS that handles the file input form data.
- var mymodule = angular.module("SampleApp",[]);
- mymodule.directive("fileInput", function($parse){
- return{
- link: function($scope, element, attrs){
- element.on("change", function(event){
- var files = event.target.files;
- $parse(attrs.id).assign($scope, element[0].files)
- $scope.$apply();
- });
- }
- }
- })
- mymodule.controller("uploadController", function ($scope, $http){
- $scope.uploadImg = function(e){
- e.preventDefault()
- var fdata = new FormData()
- angular.forEach($scope.image_file, function(file){
- fdata.append('image_file', file);
- });
- $http.post('uploadAPI.php', fdata, {
- transformRequest: angular.identity,
- headers: {'Content-Type': undefined,'Process-Data': false }
- }).then(
- function success(response){
- if(response.status == 200){
- var data = response.data
- if(data.status == 'success' ){
- //Upload is successful
- }else{
- //Upload is unsuccesful
- }
- e.target.reset()
- $scope.getImages();
- }
- }, function error(error){
- console.error(error)
- }
- )
- }
- })
PHP API
Here's the PHP Script that uploads the image file into the server's upload directory.
- <?php
- $file = $_FILES['image_file'];
- $filename = $file_path_part['filename'];
- $extension = $file_path_part['extension'];
- // Upload Directory
- $dir = 'uploads/';
- // Iteration starting Value
- $i = 0;
- while(true){
- // Filename additional text
- $additional_txt = ($i>0) ? " ({$i})" : "";
- // Temporary new filename
- $tempname = $filename.$additional_txt.".".$extension;
- // Cheching Filename Duplicate
- // If has duplicate
- $i++;
- }else{
- // Renew Filename
- $filename = $tempname;
- // break the loop
- break;
- }
- }
- if($upload){
- }else{
- }
- }else{
- }
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
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <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>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- tbody:empty:after{
- content:'No records found'
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3" ng-app="SampleApp" ng-controller="uploadController">
- <div class="col-lg-8 col-md-10 col-sm-12 mx-auto mb-3">
- <div class="card rounded-0 shadow mb-3">
- <div class="card-header">
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <form id="uploadForm" action="" ng-submit="uploadImg($event)">
- <div class="mb-3">
- </div>
- <div class="mb-3">
- <input class="form-control form-control-sm" id="image_file" type="file" file-input accept="image/*" required>
- </div>
- </form>
- </div>
- </div>
- <div class="card-footer py-1">
- <div class="text-center">
- </div>
- </div>
- </div>
- </div>
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <div class="card rounded-0 shadow mb-3">
- <div class="card-header">
- </div>
- <div class="card-body">
- <div class="container-fluid">
- <div class="list-group">
- <a href="{{file.path}}" ng-repeat="file in files" class="list-group-item list-group-item-action" target="_blank">
- {{file.name}}
- </a>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
AngularJS
app.js
- var mymodule = angular.module("SampleApp",[]);
- /**
- * Angular Controller
- */
- mymodule.directive("fileInput", function($parse){
- return{
- link: function($scope, element, attrs){
- element.on("change", function(event){
- $scope.error = false
- $scope.error_msg = ''
- $scope.success = false
- $scope.success_msg = ''
- var files = event.target.files;
- $parse(attrs.id).assign($scope, element[0].files)
- $scope.$apply();
- });
- }
- }
- })
- var upload_ctrler = mymodule.controller("uploadController", function ($scope, $http){
- $scope.error = false
- $scope.error_msg = ''
- $scope.success = false
- $scope.success_msg = ''
- $scope.files = {}
- /**
- * Trigger Upload Image
- * @param {int} page
- */
- $scope.uploadImg = function(e){
- e.preventDefault()
- $scope.error = false
- $scope.error_msg = ''
- $scope.success = false
- $scope.success_msg = ''
- var fdata = new FormData()
- angular.forEach($scope.image_file, function(file){
- fdata.append('image_file', file);
- });
- $http.post('upload_img.php', fdata, {
- transformRequest: angular.identity,
- headers: {'Content-Type': undefined,'Process-Data': false }
- }).then(
- function success(response){
- if(response.status == 200){
- var data = response.data
- if(data.status == 'success' ){
- $scope.success = true;
- $scope.success_msg = 'Image has been uploaded successfully';
- }else{
- $scope.error = true;
- if(!!data.error){
- $scope.error_msg = data.error;
- }else{
- $scope.error_msg = "Failed to upload image due to some errors.";
- }
- }
- e.target.reset()
- $scope.getImages();
- }
- }, function error(error){
- console.error(error)
- }
- )
- }
- $scope.getImages = function(){
- $http({
- method:'GET',
- url:"getImages.php"
- }).then(
- function success(response){
- if(response.status == 200){
- $scope.files = response.data
- }
- }, function error(error){
- console.error(error)
- }
- )
- }
- $scope.getImages();
- })
PHP API
upload_img.php
- <?php
- $file = $_FILES['image_file'];
- $filename = $file_path_part['filename'];
- $extension = $file_path_part['extension'];
- // Upload Directory
- $dir = 'uploads/';
- // Iteration starting Value
- $i = 0;
- while(true){
- // Filename additional text
- $additional_txt = ($i>0) ? " ({$i})" : "";
- // Temporary new filename
- $tempname = $filename.$additional_txt.".".$extension;
- // Cheching Filename Duplicate
- // If has duplicate
- $i++;
- }else{
- // Renew Filename
- $filename = $tempname;
- // break the loop
- break;
- }
- }
- if($upload){
- }else{
- }
- }else{
- }
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
Uploaded Images List
Overall Page Interface
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
- 338 views