1

I am trying to upload file using AngularJS on client side and Spring RESTApi on server side but getting

Error

org.springframework.web.multipart.MultipartException: The current request is not a multipart request
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.assertIsMultipartRequest(RequestParamMethodArgumentResolver.java:216)
    at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:167)

    .......

[http-bio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - Request method 'POST' not supported  

Rest API

Below is a simple Java Post function:

@RequestMapping(method = RequestMethod.POST)
public String saveFile(
        @RequestParam("file") MultipartFile file) {
    return "success";
}

In Angular, I am using Resource service to send request.

Chrome Developer Tool output

Request Payload
------WebKitFormBoundarydFRgXclyfPVixdHo
Content-Disposition: form-data; name="file"; filename="Release_Notes.txt"
Content-Type: text/plain


------WebKitFormBoundarydFRgXclyfPVixdHo--

Angular Service

  function FileUploadService($resource) {
    return $resource('/fileUpload/:id', {}, {
        'save' : {
            method : 'POST',
            transformRequest: function(data, headersGetter) {
                var headers = headersGetter();
                headers['Content-Type'] = undefined;

                if (data == undefined) {
                  return data;
                }

                var fd = new FormData();

                var createKey = function(_keys_, currentKey) {
                  var keys = angular.copy(_keys_);
                  keys.push(currentKey);
                  var formKey = keys.shift()

                  if (keys.length) {
                    formKey += "[" + keys.join("][") + "]"
                  }

                  return formKey;
                };

                var addToFd = function(object, keys) {
                  angular.forEach(object, function(value, key) {
                    var formKey = createKey(keys, key);

                    if (value instanceof File) {
                      fd.append(formKey, value);
                    } else if (value instanceof FileList) {
                      if (value.length == 1) {
                        fd.append(formKey, value[0]);
                      } else {
                        angular.forEach(value, function(file, index) {
                          fd.append(formKey + '[' + index + ']', file);
                        });
                      }
                    } else if (value && (typeof value == 'object' || typeof value == 'array')) {
                      var _keys = angular.copy(keys);
                      _keys.push(key)
                      addToFd(value, _keys);
                    } else {
                      fd.append(formKey, value);
                    }
                  });
                };

                addToFd(data, []);

                return fd;
              }
          }
        });
  }

Any hint to avoid this error?

3
  • can you show your rest-servlet.xml ?
    – ngCoder
    Sep 19, 2016 at 13:47
  • There is no such file in my project.
    – Moazzam
    Sep 20, 2016 at 4:12
  • ok what about app-context.xml ? That should be there as you are using springs !
    – ngCoder
    Sep 20, 2016 at 5:10

3 Answers 3

0

Method assertIsMultipartRequest from RequestParamMethodArgumentResolver class is called.

The method asserts that it is a post request and content type starts with multipart/

if (!"post".equals(request.getMethod().toLowerCase())) {
        return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));

Your content type, on the other hand, is

Content-Type: text/plain

And an exception is thrown.

1
  • Looks like you are setting it here: headers['Content-Type'] = undefined;try setting that to multipart/form-data;
    – Janar
    Sep 20, 2016 at 7:14
0
@RequestMapping(method = RequestMethod.POST)

your value attribute is missing in the requestmapping it should be like this

@RequestMapping(value="/fileupload/save/{id}" ,method = RequestMethod.POST)

and use this code when creating angular resource

$resource('fileupload/save/:id',
      {id:'1'}, {
      save: {method:'POST', params:{charge:true}}
      });

in springBoot theres not much to configure when uploading the file. but you can add these properties to your application property file to change the file size limits.

# File size limit
multipart.maxFileSize = 3Mb

# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb
1
  • We are not using Spring Boot in our project. It's a maven based spring mvc project. About value attribute, at class level, I have defined it as @RequestMapping(value = "/api/v1/fileUpload")
    – Moazzam
    Sep 20, 2016 at 4:15
0

The above issue is resolved by:

1) Creating a MultipartResolver bean in WebAppConfig.java as shown below:

@Bean
public MultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    return multipartResolver;
}

2) Replacing AngularJS FileUploadService (which is using Resource service) with http as shown below:

$http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        });

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.