1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.