AngularJS File Preview before Upload
Submitted by nurhodelta_17 on Thursday, January 4, 2018 - 15:25.
Getting Started
I've used CDN for Bootstrap and Angular JS in this tutorial so you need internet connection for them to work.Creating our HTML
This contains our input file and the place where we want our preview.- <!DOCTYPE html>
- <html >
- <head>
- <meta charset="utf-8">
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
- </head>
- <body ng-app="app" ng-controller="uploader">
- <div class="container">
- <div class="row">
- <div class="col-md-3">
- <hr>
- <input type="file" file-input="files">
- </div>
- <div class="col-md-9">
- <div ng-show="filepreview">
- <img ng-src="{{filepreview}}" height="300px" width="300px">
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
angular.js
This contains our angular.js code wherein we created a directive to handle out file input for our preview.- var app = angular.module('app', []);
- 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){
- });
Add new comment
- 486 views