我使用AngularJS與使用$ resource的REST風格的Web服務(使用spring引導運行)進行通信。我想上傳一些文件和相同的多POST請求內發送表單字段,但我得到以下錯誤:
"Unsupported Media Type" exception: "org.springframework.web.HttpMediaTypeNotSupportedException" message: "Content type 'application/xml' not supported" path: "/study/upload" status: 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);
});
}
gallery.service:
(function() {
'嚴格使用'; ('GalleryService',GalleryService);或者,您可以使用以下功能:
功能GalleryService($資源,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";
}