szark
szark

Reputation: 87

java angularjs spring file upload

I am trying to upload a file to a server using angularjs and Spring (to Amazon AWS). I checked a couple of posts on uploading with the first one and the latter but I still can't get the both to work together.

File Upload using AngularJS

How to upload a file with AngularJS?

Checked also youtube for tutorials, found Black Cloud, Brent Aureli's channel and I just cannot figure it out.

You have to be authenticated in my webapp to send post requests, but I am getting errors also when I'm logged in.

Would be extremely grateful for some help.

This is my html form:

<form>
<input type="file" file-model="file">
<button ng-click="submit()" type="submit">Click</button>
</form>

Directive for the file-model:

.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[0]);
                })
            })
        }
    }
}])

Controller:

.controller('UploadController', ['$scope', 'multipartForm', function($scope, multipartForm) {
    $scope.file = {}; 
    $scope.submit = function() {
        var uploadUrl = '/uploadtest';
        multipartForm.post(uploadUrl, $scope.file);
    }       
}])

Service for multipartForm:

.service('multipartForm', ['$http', function($http){
    this.post = function(uploadUrl, data) {
        var fd = new FormData();
        for(var key in data) {
            fd.append(key, data[key]);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
    }
}])

Spring Endpoint:

@RestController
@RequestMapping("/storage/")
public class BucketController {

    private AmazonClient amazonClient;

    @Autowired
    public BucketController(AmazonClient amazonClient) {
        this.amazonClient = amazonClient;
    }

    @RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
    public String uploadFile(@RequestParam(value = "file") MultipartFile file) {
        System.out.println("Uploading file!!!!!!!!!!!!");
        return this.amazonClient.uploadFile(file);
    }  
}

Error that I'm getting in the browser:

angular.js:15018 Possibly unhandled rejection: {"data":{"timestamp":1537033312586,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/uploadtest"}, "status":400, "config":{"method":"POST","transformResponse":[null], "jsonpCallbackParam":"callback", "headers":{"Accept":"application/json, text/plain, /", "X-Requested-With":"XMLHttpRequest", "Authorization": "Basic c3p5bW9uc3R1c3pla0BnbWFpbC5jb206dGVzdA==", "X-XSRF-TOKEN":"395d1e27-a6ee-4948-b673-39d31902e1ae"}, "url":"/uploadtest","data":{}}, "statusText":"","xhrStatus":"complete"}

Upvotes: 0

Views: 481

Answers (1)

Ravikumar Rajendran
Ravikumar Rajendran

Reputation: 504

The exception occurred due the missing query param 'file' which is not presented. And in spring endpoint you should not receive a file request in Request param!

    @RequestMapping(value="/uploadtest", consumes = "multipart/form-data",method = RequestMethod.POST, produces = "application/json")
        public String uploadFile(MultipartHttpServletRequest  request) throws Exception{

      try {
            MultipartFile multipartFile1 = request.getFile("file");
            if (multipartFile1 != null) {
                 String file1 = multipartFile1.getOriginalFilename();
                 InputStream inputStream = multipartFile1.getInputStream();
                // do whatever 
            }
         } catch (IOException e) {
            logger.error(e.getMessage());
        }
    return null;
}

And in Service for multipartForm change the headers content-type to : multipart/form-data

Hope this would Help!!

Upvotes: 1

Related Questions