File pick with Angular JS

后端 未结 8 752
时光取名叫无心
时光取名叫无心 2020-12-08 07:50

I would like to pick up a file with AngularJS:

HTML:

相关标签:
8条回答
  • 2020-12-08 08:26

    Following is my approach with a directive.

    Directive

    angular
      .module('yourModule')
      .directive('fileChange', function() {
        return {
         restrict: 'A',
         scope: {
           handler: '&'
         },
         link: function (scope, element) {
          element.on('change', function (event) {
            scope.$apply(function(){
              scope.handler({files: event.target.files});
            });
          });
         }
        };
    });
    

    HTML

    <input type="file" file-change handler="fileSelect(files)">
    

    Controller

    fileSelect = function (files) {
          var file = files[0];
          //you will get the file object here
    }
    
    0 讨论(0)
  • 2020-12-08 08:31

    Using Madura's answer from above, here's the complete flow for reading a local JSON file:

    Create directive:

    angular
      .module('app.services')
      .directive('fileChange', function() {
        return {
         restrict: 'A',
         scope: {
           handler: '&'
         },
         link: function (scope, element) {
          element.on('change', function (event) {
            scope.$apply(function(){
              scope.handler({files: event.target.files});
            });
          });
         }
        };
    });
    

    HTML:

    <input type="file" file-change handler="fileSelect(files)">
    

    Javascript:

    $scope.fileSelect = function(files) {
      var file = files[0];
      var reader = new FileReader();
      reader.onload = function(e) {
        console.log("on load", e.target.result);
      }
      reader.readAsText(file);
    }
    
    0 讨论(0)
提交回复
热议问题