Search code examples
angularjsspringmultipart

MultipartFile and String in Post Parameter


Probably this might be the basic question but I could not get the solution when I tried from various answered provided in stackoverflow.

Question:

I need to send a file from my angular to the server. I asked the same question in stackoverflow and it can be found here,

Using Multipart without Form in Spring MVC

Now the question is, I want to send one more object (which is not a file, probably a JSON) to the server. How should I do it?

I have tried wrapping up Multipart file and also JSON object into one and sending it but the attempt was not successful as spring slapped me with some exception. First of all, Is my approach correct? If it is not then how should I go ahead?


Solution

  • I got the solution by using RequestPart annotation in the controller definition,

    Thanks to https://stackoverflow.com/a/30043173/3121941 . It provided me insights to solve the problem.

    The Updated code,

    @RequestMapping(value = "/someUrl", method = RequestMethod.POST, consumes = {
                "multipart/form-data", MediaType.APPLICATION_JSON_VALUE })
        public Object handleUpload(
                @RequestPart("paramOne") String paramOne,
                @RequestPart("paramTwo") String paramTwo,
                @RequestPart("file") MultipartFile file, Principal user){
    

    And My Angular code is,

    $scope.upload = function () {
            var file = $scope.file;
            var obj = new Object();
            var fd = new FormData();
            fd.append("paramOne","xyz");
            fd.append("paramTwo","xyz");
            fd.append("file", file);        
            var uploadUrl = "/someUrl";
            $http.post(uploadUrl, fd, {
                transformRequest: angular.identity,
                headers: {
                    'Content-Type': undefined
                }
            }).success(function (data) {
                    console.log("Call successful");
            });
        }