繁体   English   中英

使用Angular将多个文件上传到Spring Controller

[英]Upload multiple files with Angular to Spring Controller

我想将多个文件上传到服务器。 这是我的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);
                });
            });
        }
    };
}]);

以及部分控制器:

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

问题是在控制器中:

public void createTicket(@RequestParam(value = "files", required = false) List<MultipartFile> files,
                         Authentication authentication,
                         @RequestParam(value = "ticketDto", required = false) String name)

“文件”列表始终为空(我也尝试使用MultipartFile []而不是列表)。 它仅在指令返回的文件不是所有文件而是一个文件的情况下才有效,例如:

scope.$apply(function () {
    modelSetter(scope, element[0].files[0]);
});

代替

scope.$apply(function () {
    modelSetter(scope, element[0].files);
});

终于我明白了。 解决方案是将所有文件分开添加到FormData中,而不是列表或数组中:

angular.forEach($scope.file, function (value, key) {
            fd.append('files', value);
        })

然后在Spring控制器中:

public void createTicket(@RequestParam(required = false) MultipartFile[] files)

该数组包含所有附加文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM