Thursday 16 February 2017

Show preview image while uploading

Here (File upload and sending data to backend using angular js)we have discussed about uploading file/image, let us check how we can show a preview image while uploading. I am not putting all file upload code here, if you are interested check here.


Preview of image while uploading



<form name="upload" class="form" ng-submit="addFile()">
  <input type="file" name="file" id="iconUplaod" multiple 
 onchange="angular.element(this).scope().uploadedFile(this)" />
 <button type="submit">Upload </button>
</form>


JS



$scope.uploadedFile = function(element) {
 $scope.$apply(function($scope) {
   $scope.files = element.files;
   //icon preview
   var fileReader = new FileReader();
   fileReader.readAsDataURL(document.getElementById("iconUplaod").files[0]);
   fileReader.onload = function (oFREvent) {
 $timeout(function(){
   $scope.iconPreviewUrl = oFREvent.target.result;
 });
   };
 });
}


You can show this preview url anywhere you want.


<img ng-src="{{iconPreviewUrl}}" alt=""/>

As mentioned above it is very straight forward, in case you want to show file name as well please check below code

Show uploaded file name



$scope.uploadedFile = function(element) {
  if(element.files.length > 1){
   $scope.iconDetails = element.files.length + 'files';
  }
  else{
   $scope.iconDetails = element.files[0].name;
  }
}


Show this where ever you want.


<p>{{iconDetails}}</p>


Related Post

1. File upload validation

2. File upload and sending data to backend using angular js

3. How to download file from backend to UI

No comments :

Post a Comment