[英]Upload multiple files with Angular to Spring Controller
I want to upload to server multiple files. 我想将多个文件上传到服务器。 Here is my Angular code:
这是我的Angular代码:
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files);
});
});
}
};
}]);
And part of the controller: 以及部分控制器:
var fd = new FormData();
fd.append('files', $scope.file);
fd.append('ticketDto', JSON.stringify(data));
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': undefined
},
data: fd,
arrayKey: '',
transformRequest: function (data, headersGetterFunction) {
return data;
}
})
The problem is that in controller: 问题是在控制器中:
public void createTicket(@RequestParam(value = "files", required = false) List<MultipartFile> files,
Authentication authentication,
@RequestParam(value = "ticketDto", required = false) String name)
'files' list is always empty (I also tried MultipartFile[] instead of list). “文件”列表始终为空(我也尝试使用MultipartFile []而不是列表)。 It works only if in directive return not all files, but one, for example:
它仅在指令返回的文件不是所有文件而是一个文件的情况下才有效,例如:
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
instead of 代替
scope.$apply(function () {
modelSetter(scope, element[0].files);
});
Finally I got it. 终于我明白了。 The solution is to add all files to the FormData apart, not as list or array:
解决方案是将所有文件分开添加到FormData中,而不是列表或数组中:
angular.forEach($scope.file, function (value, key) {
fd.append('files', value);
})
And then in Spring controller: 然后在Spring控制器中:
public void createTicket(@RequestParam(required = false) MultipartFile[] files)
The array contains all appended files. 该数组包含所有附加文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.