Java AngularJS + Spring:415 不支持的媒体类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20950346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:30:46  来源:igfitidea点击:

AngularJS + Spring: 415 unsupported media type

javaspringangularjshttp-postmultipartform-data

提问by Satish

http post is getting error while uploading multipart data

上传多部分数据时http post出错

var formData = new FormData();

formData.append("startDate",$("#startDate").val());
formData.append("File1",$("input[name='file']")[0].files[0]);
formData.append("File2",$("input[name='file2']")[0].files[0]);

$http.post("sampleurl",formData,
{ headers : 'Content-Type' : undefined},
transformRequest : angular.identity
}).then(function(data){
  alert(data);
    });
}

my server side code is

我的服务器端代码是

@RequestMapping(value = "sampleurl", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON)
    public @ResponseBody
    Response createSomething(
            @RequestBody Request request,
            HttpServletRequest httpServletRequest,
            HttpServletResponse httpServletResponse) {
            // code here
    }

what went wrong here, i am stucked to find the solution, please help me to find the solution

这里出了什么问题,我一直在寻找解决方案,请帮我找到解决方案

采纳答案by Mickael

An http error 415 means that content of request is not in the appropriate format.

http 错误 415 表示请求的内容格式不正确。

Spring MVC '@RequestBody' expect a json body (with a Content-Type equal to 'application/json') and you explicitly set your Content-Type to undefined.

Spring MVC '@RequestBody' 需要一个 json 主体(Content-Type 等于 'application/json'),并且您将 Content-Type 显式设置为未定义。

The solution is to set your content-type to 'application/json' in your post request or to remove @RequestBody annotation.

解决方案是在您的发布请求中将您的内容类型设置为 'application/json' 或删除 @RequestBody 注释。

It seems that you try to upload files, the easier would be to remove @RequestBody annotation.

似乎您尝试上传文件,删除 @RequestBody 注释会更容易。

回答by Michal Gajdos

You should be sending multipart/form-dataand not undefinedvalue in your Content-Typeheader (Acceptheader sent from client should be application/json). Also make sure that the method on the server side consumes this particular media type.

您应该在您的标头中发送multipart/form-data而不是undefinedContent-TypeAccept从客户端发送的标头应该是application/json)。还要确保服务器端的方法使用这种特定的媒体类型。