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

AngularJS - upload and display image using FileReader API (multiple files)

我使用下面的例子,效果很好,但是我想同时上传多张图片。

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

开始的

解决方案:

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);
    });
}

Zypps987,尝试使用 var file = files[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 元素的文件 属性 更新模型。

此指令使 <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>