article

Thursday, January 6, 2022

AngularJS Preview before Upload

AngularJS Preview before Upload

angularjs CDN https://angularjs.org/ Version 1.8.2 https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js

//index.html
<!DOCTYPE html>
<html >
<head>
	<title>AngularJS Preview before Upload</title>
	<meta charset="utf-8">
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>  
</head>
<body ng-app="angularupload" ng-controller="uploader">
<div class="container">
	<h1 class="page-header text-center">AngularJS Preview before Upload</h1>
	<div class="row">
		<div class="col-md-3">
			<h3 class="text-center">Upload File</h3>
			<hr>
			<label>File:</label>
			<input type="file" file-input="files">
		</div>
		<div class="col-md-9">
			<div ng-show="filepreview">
			<img ng-src="{{filepreview}}" height="300px" width="300px">
			<h4>Filename: {{ name }}</h4>
			<h4>Size: {{ size }}</h4>
			</div>
		</div>
	</div>
</div>
<script>
var app = angular.module('angularupload', []);
app.directive('fileInput', ['$parse', function ($parse) {
	return {
      $scope: {
        fileinput: "=",
        filepreview: "="
      },
      link: function($scope, element, attributes) {
        element.bind("change", function(changeEvent) {
          	$scope.fileinput = changeEvent.target.files[0];
          	var reader = new FileReader();
          	reader.onload = function(loadEvent) {
            	$scope.$apply(function() {
            		$scope.filepreview = loadEvent.target.result;
            	});
          	}
          	reader.readAsDataURL($scope.fileinput);
          	$scope.name = $scope.fileinput.name;
          	$scope.size = $scope.fileinput.size;
        });
      }
    }
}]);
app.controller('uploader', function($scope, $http){

});
</script>
</body>
</html>

Related Post