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