415 (Unsupported Media type) when trying to post formData to Spring

I want to post pdf files to spring, using formData.

Javascript Code:

var formData=new FormData();
formData.append("file",file);

  $http({
    method: 'POST',
    accept: 'multipart/form-data',
    url: '/upload',
    contentType: 'multipart/form-data',
    data: formData
  }).then(function successCallback(response) {
    console.log(response);
  }, function errorCallback(response) {
    console.log(response);
  });

Spring Code:

@Controller
public class upload {


@RequestMapping(value = "/upload", method = RequestMethod.POST,consumes="multipart/form-data", headers = "content-type=multipart/form-data")
private void upload(MultipartHttpServletRequest request, HttpServletResponse response){

}
}

I get the Error "415 (Unsupported Media Type)" when using this code. I tried to post json objects (application/json instead of multipart/form-data) and it worked perfectly.

Is multipart/form-data the wrong type to use in my case? Or is there just an error in the code?

I would be very thankful for potential help.


The Accept part is wrong, you don't need that.

$http don't handle that much files natively, use https://github.com/danialfarid/ng-file-upload in order to be able to handle files, add validation on your form about the files (size, type, ...).

For a raw $http solution check the 2nd most upvated answer here : Angularjs $http post file and form data

链接地址: http://www.djcxy.com/p/48726.html

上一篇: Spring Boot中的文件上传:上传,验证和异常处理

下一篇: 415(不支持的媒体类型)尝试将formData发布到Spring时