<input type="file" ng-model="item.files" ng-change="item.onSelectFile()"/>
function MyController($scope, httpSrvc){
function Item(){
this.name = "";
this.files = [];
this.onSelectFile = function(file){
if(this.files.length < 3){
this.files.push(file);
}
}
this.onSubmit = function(){
let formData = new FormData();
formData.append("name",this.name);
for(let i = 0 ; i < this.files.length ; i++){
formData.append(`page_${i+1}`,this.files[i]);
}
httpSrvc.post(url,formData)
.then(function(res){console.log(res)})
.catch(function(err){console.log(err)})
}
}
function init(){
$scope.item = new Item();
}
}
是否可以将文件存储在数组中?我应该为ng-model设置什么值?
答案 0 :(得分:1)
检查以下代码。
注意事项:
onchange
事件并使用angular.element(this).scope()
获取范围$scope.$apply
中。如果要在视图上显示文件列表,这是必需的。这是必要的,因为files
数组没有被角度跟踪,因为它没有分配为ng-model
。'Content-Type': undefined
中需要http headers
angular.module('myApp', []).controller('MyController', ['$scope', '$http',
function MyController($scope, $http) {
function Item() {
this.name = "";
this.files = [];
this.onSelectFile = function(event) {
$scope.$apply(() => {
let file = event.target.files[0];
if (this.files.length < 3) {
this.files.push(file);
}
});
}
this.onSubmit = function() {
let formData = new FormData();
formData.append("name", this.name);
for (let i = 0; i < this.files.length; i++) {
formData.append(`page_${i+1}`, this.files[i]);
}
let url = "www.google.com";
let request = {
method: 'POST',
url: url,
data: formData,
headers: {
'Content-Type': undefined
}
};
$http(request)
.then(function(res) {
console.log(res)
})
.catch(function(err) {
console.log(err)
})
}
}
function init() {
$scope.item = new Item();
}
init();
document.querySelector('input[type="file"]').addEventListener('change', (event) => $scope.item.onSelectFile(event));
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyController">
<input type="file" ng-model="item.file" />
<ul>
<li ng-repeat="file in item.files">
{{ file.name }}
</li>
</ul>
<input type="button" value="Submit" ng-click="item.onSubmit()">
</div>