-4

How to upload document of any type like .txt, jpeg or gif and get preview in html page? Only by using HTML5 and AngularJS. No need to save document at any location.

1
  • 1
    What have you tried so far? It would be good to show the code you've been working on. Commented Aug 31, 2017 at 6:54

1 Answer 1

1

You can use the FileReader API to read the data in the file.

This example modifies the above linked answer and checks if the file type is an image and displays it as such. Otherwise, it displays the file's data as text.

angular.module('fileLoad', []).directive('fileSelect', ['$window', function($window) { return { restrict: 'A', require: 'ngModel', link: function($scope, el, attr, ctrl) { var fileReader = new $window.FileReader(); var fileType; fileReader.onload = function() { var fileData = {}; fileData.type = fileType; fileData.data = fileReader.result; ctrl.$setViewValue(fileData); $scope.$apply(); }; el.bind('change', function(e) { var fileName = e.target.files[0]; fileType = (fileName && fileName.type) || ''; if (fileType.indexOf('image') != -1) { fileReader.readAsDataURL(fileName); } else if(fileName) { fileReader.readAsText(fileName); } else { ctrl.$setViewValue({}); $scope.$apply(); } }); } }; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="fileLoad"> <input type="file" ng-model="file.data" file-select> <img ng-show="file.data.type && file.data.type.indexOf('image') != -1" data-ng-src="{{file.data.data}}" /> <p ng-show="file.data.type && file.data.type.indexOf('image') == -1" ng-bind="file.data.data"></p> </div>

Sign up to request clarification or add additional context in comments.

1 Comment

It is HTML and java script.But i need in Angular Js.Please help me ASAP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.