Preview image before downloading Angularjs

Hi, I was wondering if there is a way to preview the images before I upload them using angularjs? I am using this library. https://github.com/danialfarid/angular-file-upload

Thank. Here is my code:

template.html

<div ng-controller="picUploadCtr"> <form> <input type="text" ng-model="myModelObj"> <input type="file" ng-file-select="onFileSelect($files)" > <input type="file" ng-file-select="onFileSelect($files)" multiple> </form> </div> 

controller.js

  .controller('picUploadCtr', function($scope, $http,$location, userSettingsService) { $scope.onFileSelect = function($files) { //$files: an array of files selected, each file has name, size, and type. for (var i = 0; i < $files.length; i++) { var $file = $files[i]; $http.uploadFile({ url: 'server/upload/url', //upload.PHP , node.js route, or servlet uplaod url) data: {myObj: $scope.myModelObj}, file: $file }).then(function(data, status, headers, config) { // file is uploaded successfully console.log(data); }); } } 
+46
angularjs ajax upload file-upload angularjs-directive
Sep 12 '13 at 3:41 on
source share
4 answers

OdeToCode has published an excellent service for this. Thus, with this simple directive, you can easily view and even see the progress bar:

 .directive("ngFileSelect",function(){ return { link: function($scope,el){ el.bind("change", function(e){ $scope.file = (e.srcElement || e.target).files[0]; $scope.getFile(); }); } } 

It works in all modern browsers!

Example: http://plnkr.co/edit/y5n16v?p=preview

+49
01 Oct '13 at 6:35
source share

Javascript

  $scope.setFile = function(element) { $scope.currentFile = element.files[0]; var reader = new FileReader(); reader.onload = function(event) { $scope.image_source = event.target.result $scope.$apply() } // when the file is read it triggers the onload event above. reader.readAsDataURL(element.files[0]); } 

Html

 <img ng-src="{{image_source}}"> <input type="file" id="trigger" class="ng-hide" onchange="angular.element(this).scope().setFile(this)" accept="image/*"> 

It worked for me.

+32
Aug 11 '15 at 10:12
source share

See Image Upload Widget from Jasney Extension for Bootstrap v3

+9
Jan 20 '14 at 1:12
source share
  // start Picture Preview $scope.imageUpload = function (event) { var files = event.target.files; for (var i = 0; i < files.length; i++) { var file = files[i]; var reader = new FileReader(); reader.onload = $scope.imageIsLoaded; reader.readAsDataURL(file); } } $scope.imageIsLoaded = function (e) { $scope.$apply(function () { $scope.img = e.target.result; }); } <input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(event)" /> <img class="thumb" ng-src="{{img}}" /> 
+3
Jan 15 '17 at 10:58
source share



All Articles