0

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.

JS

myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
             $scope.uploadFile = function(){
                    var formData=new FormData();
                    formData.append("file", $scope.myFile); 
                    alert("Hi");
                    $http({
                        method: 'POST',
                        url: 'upload', 
                        headers: {'Content-Type': undefined}, 
                        data: formData,
                        transformRequest: function(data, headersGetterFunction) {
                            return data;
                        }
                    }).success(function(data, status) {  
                         console.log('file is ' );
                         console.dir(data);
                    })
                    .error(function(data, status) {
                    });
                }
         }]);

Spring-REST Controller

 @RequestMapping(value="/upload", method=RequestMethod.POST)
         public @ResponseBody String upload(@RequestBody MultipartFile file)  {
                        System.out.println(file);
}

I also tried with public @ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.

Protagonist
  • 1,649
  • 7
  • 34
  • 56

1 Answers1

0

Here is a piece of code that works for me:

Spring-REST Controller

@RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
@ResponseBody
public boolean uploadUserImage( @PathVariable("id") Long id, @RequestParam("file") MultipartFile file ) {
    return userService.saveUserImage(id, file);
}

and on the front-end you could do something like this

Angular Controller

//the image
$scope.uploadme;

$scope.uploadImage = function() {
  var fd = new FormData();
  var imgBlob = dataURItoBlob($scope.uploadme);
  fd.append('file', imgBlob);
  $http.post(
      '/upload',
      fd, {
        transformRequest: angular.identity,
        headers: {
          'Content-Type': undefined
        }
      }
    )
    .success(function(response) {
      console.log('success', response);
    })
    .error(function(response) {
      console.log('error', response);
    });
}


//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
  var binary = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var array = [];
  for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
  }
  return new Blob([new Uint8Array(array)], {
    type: mimeString
  });
}

Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(@RequestBody MultipartFile file) to upload(@RequestParam("file") MultipartFile file). So it will be like this:

@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public void upload(@RequestParam("file") MultipartFile file)  {
    System.out.println(file);
}

Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.

Lastly you could check this answer that i gave to a similar problem.

Community
  • 1
  • 1
Christos Baziotis
  • 5,845
  • 16
  • 59
  • 80