简体   繁体   English

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

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

I want to post pdf files to spring, using formData. 我想使用formData将pdf文件发布到春天。

Javascript Code: JavaScript代码:

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. 使用此代码时出现错误“ 415(不支持的媒体类型)” I tried to post json objects (application/json instead of multipart/form-data) and it worked perfectly. 我试图发布json对象(应用程序/ json而不是multipart / form-data),并且效果很好。

Is multipart/form-data the wrong type to use in my case? 在我的情况下,multipart / form-data是否使用了错误的类型? 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, ...). $ http本身不会处理那么多文件,请使用https://github.com/danialfarid/ng-file-upload以便处理文件,并在表单上添加有关文件的验证(大小,类型,。 ..)。

For a raw $http solution check the 2nd most upvated answer here : Angularjs $http post file and form data 对于原始的$ http解决方案,请在此处查看第二个最高级的答案: Angularjs $ http发布文件和表单数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM