Moazzam Moazzam - 2 months ago 112
reST (reStructuredText) Question

The current request is not a multipart request in angularJS and Spring Rest

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?

Answer

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.