0

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"}

1 Answer 1

1

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!!

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

3 Comments

thanks a lot Ravikumar for the help!! with your advice, the frontend started to communicate with the spring controller :) unfortunately it is not the end of the issues. I added the attribute name="file" in my form. Deleted @RequestMapping("/storage/") from the controller. The controler is getting now the request, but when I try to get the file: request.getFile("file") It appears to be null. When changing to multipart/form-data in services I have to set up boundaries and I'm not sure how to handle with that. So it's communicating now but I cannot get the file from the request.
@szark did you try sending like this stackoverflow.com/questions/35722093/…
hi Ravikumar, I did some more searching and I found a working piece of code for me, I googled: grokonez Spring AngularJs MultipartFile application to download/upload files. I just need to do a couple more tutorials, to get a better understanding of how the communication between angularjs and spring works, especially for file upload. Thanks for the help again! :)

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.