【发布时间】:2017-06-07 06:35:33
【问题描述】:
我正在 AngularJS 中开发一个文件上传模块。我将拥有多个文件控件,每个控件一次可以上传一个文件(不是多个)。最后点击提交,我保存了所有文件。我正在使用ng-repeat 动态生成文件控件,如下所示。
<div class="upload-button" ng-repeat="fileInput in fileInputs">
<div class="upload-button-icon">
<img src="images/folder-small.png">
<div class="upload-text">{{fileInput}}</div>
<input type="file" file-data="{{fileInput}}" file-model="{{fileInput}}" />
</div>
</div>
为文件控件赋值的JS代码
$scope.fileInputs = ["Passport","Visa"];
下面是我上传文件的代码。
myapp.factory('fileUpload', ['$http', function ($http) {
var fileuploadurl = "http://localhost:19144/" + 'api/Customer/UploadLeaseFiles/' + 2;
var service = {
uploadUrl: fileuploadurl,
pendingFiles: [],
doUpload: doUpload
};
return service;
function doUpload() {
debugger;
var files = new FormData();
angular.forEach(this.pendingFiles, function (value, index) {
files.append('file', value);
files.append('IndexValue', index);
});
return $http.post(this.uploadUrl, files, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
})
}
}]);
这是我的指令代码。
myapp.directive('fileModel', ['fileUpload', function (fileUpload) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.bind("change", function (evt) {
fileUpload.pendingFiles[attrs.fileModel] = evt.target.files[0];
});
}
};
}]);
仅当我将整数分配给 fileInputs 时,上述代码才有效:
$scope.fileInputs = [1,2,3];
如果我将整数分配给文件输入,我很难理解为什么它会起作用。如何分配字符串并使上述代码工作?
【问题讨论】:
-
您正在尝试访问
pendingFiles。你在哪里定义它? -
谢谢。是的。请参阅指令文件模型。它需要文件。
-
不确定我是否得到了你。注入指令的
fileUpload是什么 -
嘿,您正在尝试将文件放入数组中。因此,使用数字它会正常工作,因为数字可以是 indexex。你不能只让字符串成为索引
-
哦,谢谢。有没有替代解决方案来解决这个问题?我会得到 $scope.fileInputs = ["Passport","Visa"];
标签: angularjs