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
- <!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" class="form-control" accept="image/*" onchange="angular.element(this).scope().uploadedFile(this)">
- <button ng-click = "uploadFile()">upload me</button>
- <br/>
- <img ng-src="{{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.
- <?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";
- }
- ?>