angular input file 上传文件

<body >
<div ng-controller="fileCtrl">
  <form ng-submit="submit(obj)">
  <input type="file" ng-file-model="obj.testFile" />
  <input type="submit"  value="submit" />
  </form>
  Submitted File :
  <pre>
  
  </pre>
  </div>
  <script>
  angular.module("myApp", [])
      .controller("fileCtrl",["$scope", function($scope){
      $scope.submittedFile = {};
      $scope.obj = {};
      $scope.submit = function(obj){
      console.log(JSON.stringify(obj.testFile))
      
      }
      }])

    .directive("ngFileModel", [function () {
        return {
            scope: {
                ngFileModel: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var reader = new FileReader();
                    reader.onload = function (loadEvent) {
                        scope.$apply(function () {
                            scope.ngFileModel = {
                                lastModified: changeEvent.target.files[0].lastModified,
                                lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
                                name: changeEvent.target.files[0].name,
                                size: changeEvent.target.files[0].size,
                                type: changeEvent.target.files[0].type,
                                data: loadEvent.target.result
                            };
                        });
                    }
                    reader.readAsDataURL(changeEvent.target.files[0]);
                });
            }
        }
    }]);
  </script>
</body>

 

posted @ 2016-05-05 22:57  cench  阅读(1968)  评论(0编辑  收藏  举报