【发布时间】:2016-08-01 22:20:27
【问题描述】:
我正在使用 AngularJS 与 RESTful Web 服务(使用 Spring Boot 运行)进行通信,使用 $resource。我正在尝试在同一个多部分发布请求中上传一些文件并发送表单字段,但出现以下错误:
“不支持的媒体类型”异常: “org.springframework.web.HttpMediaTypeNotSupportedException”消息: “不支持内容类型‘application/xml’”路径:“/study/upload” 状态:415
这是我的视图:
<form method="post" enctype="multipart/form-data" ng-submit="submit()">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" ng-model="form.file"/></td></tr>
<tr><td>Name:</td><td><input type="text" name="name" ng-model="form.name"/></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
这里是视图控制器:
$scope.submit=function(){
GalleryService.upload({file: $scope.form.file, name: $scope.form.name}, function(data) {
console.log("Success ... " + status);
}, function(error) {
console.log(error);
});
}
画廊服务:
(function() {
'使用严格';
角度 .module('ekellsApp') .factory('GalleryService', GalleryService);
function GalleryService($resource, restApi) {
return $resource(restApi.url + '/study/:action', {},{
save: {method: 'POST', params: {action: 'save'}},
getAll: {method: 'GET', params: {action: 'getAll'},isArray:true},
upload: {method: 'POST', params: {action: 'upload'}, transformRequest: angular.identity,headers: { 'Content-Type': undefined }}
});
}
})();
这里是 REST 控制器:
@RequestMapping(value = "/upload",method = RequestMethod.POST,headers = "content-type=multipart/*")
public String handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (name.contains("/")) {
redirectAttributes.addFlashAttribute("message", "Folder separators not allowed");
return "redirect:upload";
}
if (name.contains("/")) {
redirectAttributes.addFlashAttribute("message", "Relative pathnames not allowed");
return "redirect:upload";
}
if (!file.isEmpty()) {
try {
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(new File("user/bouhuila/" + name)));
FileCopyUtils.copy(file.getInputStream(), stream);
stream.close();
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + name + "!");
}
catch (Exception e) {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + name + " => " + e.getMessage());
}
}
else {
redirectAttributes.addFlashAttribute("message",
"You failed to upload " + name + " because the file was empty");
}
return "redirect:upload";
}
【问题讨论】:
标签: angularjs spring rest spring-boot multipart