Unable to upload file from Angular client to Sprin

2019-09-10 09:11发布

问题:

When I am uploading a file from Postman rest client to the server(spring application deployed on a remote machine), I am able to upload the file without any issue.

But when I try to write a rest client in angular.js, and send over the request, I get 400 Bad Request Error. I know it's because of some syntax issue between what is send from client and what server is expecting.

Server side code:

@CrossOrigin(origins = "*") @RequestMapping(value="/upload", method=RequestMethod.POST, consumes = {"multipart/form-data"})

public @ResponseBody String handleFileUpload(@RequestParam("files") MultipartFile file){ . . . . }

Client side code:

$scope.uploadFiles = function () {
    alert("inside");

    var request = {
        method: 'POST',
        url: 'http://IP ADDRESS and PORT NUMBER/upload',
        data: formdata,
        headers: {
            'Content-Type': undefined
        }
    };


    $http(request)
        .success(function (response) {
            alert("success: "+response);

        })
        .error(function (err) {alert("error: "+err);
        });
}

回答1:

I have uploaded the code here for file upload using Spring and AngularJS:

https://gist.github.com/abdulrafique/9219f7164fdf5dc6dfa8da110be6a04e