简体   繁体   中英

Upload multiple files with Angular to Spring Controller

I want to upload to server multiple files. Here is my Angular code:

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). 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:

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

And then in Spring controller:

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

The array contains all appended files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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