Preview Image before uploading Angularjs

user1424508 picture user1424508 · Sep 12, 2013 · Viewed 79.9k times · Source

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

Thanks. 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 script, 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);
  }); 
}
}

Answer

Ivan Chernykh picture Ivan Chernykh · Oct 1, 2013

OdeToCode posted great service for this stuff. So with this simple directive you can easily preview 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 is working in all modern browsers!

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