我使用以下示例,它运行良好,但我想同时上传多个图像。
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
答案 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-change
和ng-form
指令。
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>