angularjsgrailsng-file-uploadgrails-2.5

how to use ng-file-upload with grails 2.5.3


I am trying to use ng-file-upload to upload multiple files at the same time to my grails controller action. However, I can't figure out how to get a hold of the files that are being uploaded to the action.

Here is my JS code:

app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
    $scope.uploadFiles = function (files) {
        $scope.files = files;
        if (files && files.length) {
            Upload.upload({
                url: 'http://localhost:8080/classifydemo/request/create',
                data: {
                    files: files
                }
            }).then(function (response) {
                $timeout(function () {
                    $scope.result = response.data;
                });
            }, function (response) {
                if (response.status > 0) {
                    $scope.errorMsg = response.status + ': ' + response.data;
                }
            }, function (evt) {
                $scope.progress = 
                    Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
            });
        }
    };
}]);

And my grails action is below:

class RequestController {

    def create() {
        request.headerNames.each{
           println it
        }
        println params
        println request.getFile("file")
        render "test"
    }

}

The above code fails on request.getFile.

Question

How can I get a hold of the files that are being uploaded to the controller so that I can process them in a loop.


Solution

  • Since you have the possibility of multiple files you should use:

    request.fileNames.each {
      MultipartFile file = request.getFile(it)
      // do whatever you want with the file
    }