AngularJS - 使用FileReader API上传和显示图像(多个文件)

时间:2015-07-27 23:56:05

标签: angularjs file upload filereader

我使用以下示例,它运行良好,但我想同时上传多个图像。

http://jsfiddle.net/kkhxsgLu/2/

<div ng-controller="MyCtrl">

<div ng-repeat="step in stepsModel">
    <img class="thumb" ng-src="{{step}}" />
</div>

<input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(this)" />

 $scope.stepsModel = [];

$scope.imageUpload = function(element){
    var reader = new FileReader();
    reader.onload = $scope.imageIsLoaded;
    reader.readAsDataURL(element.files[0]);
}

$scope.imageIsLoaded = function(e){
    $scope.$apply(function() {
        $scope.stepsModel.push(e.target.result);
    });
}

谢谢你,帮助我,我开始使用angularjs

3 个答案:

答案 0 :(得分:18)

SOLUTION:

http://jsfiddle.net/orion514/kkhxsgLu/136/

:)

<div ng-controller="MyCtrl">

<div ng-repeat="step in stepsModel">
    <img class="thumb" ng-src="{{step}}" />
</div>

<input type='file' ng-model-instant 
       onchange="angular.element(this).scope().imageUpload(event)"
       multiple />

$scope.stepsModel = [];

$scope.imageUpload = function(event){
     var files = event.target.files; //FileList object

     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.stepsModel.push(e.target.result);
    });
}

答案 1 :(得分:0)

Zypps987,尝试使用var file = files [0],而不是在循环内。

答案 2 :(得分:0)

使用ng-model(多个文件)

输入文件的指令

AngularJS内置<input>指令不处理<input type=file>。人们需要一个自定义指令。

<input type="file" files-input ng-model="fileArray" multiple>

files-input指令:

angular.module("app").directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
})

上面的指令添加了一个更改侦听器,它使用input元素的files属性更新模型。

该指令使<input type=file>能够自动使用ng-changeng-form指令。

DEMO on PLNKR

files-input指令的内联演示

angular.module("app",[]);

angular.module("app").directive("filesInput", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" files-input ng-model="fileArray" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileArray">
      {{file.name}}
    </div>
  </body>