为什么angularJs文件上传失败到后端数据发送到春天控制器? [英] Why angularJs file upload is failing to send data to spring controller at backend?
本文介绍了为什么angularJs文件上传失败到后端数据发送到春天控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从前端上传文件在数据库中保存。但春天控制器未能接收文件。
I'm trying to upload a file from front end to save in the database. But Spring controller is failing to receive the file.
HTML
<html>
<title>FILE_OLPV</title>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script type="text/javascript" src="js/abc.js"></script>
</body>
</html>
JS
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = 'fileUpload';
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
春季控制器
@RequestMapping(value="/fileUpload", method=RequestMethod.POST)
public @ResponseBody String upload(@RequestParam("file") MultipartFile file ) throws IOException {
System.out.println("HEEEEEEEEEEEEEEEEEEEE");
MultipartFile file1 = file;
System.out.println(file1);
System.out.println("Inside for loop");
}
Configuaration.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"/>
</bean>
这是未达到春季控制器。对此有何想法?
It is failing to reach the Spring controller. Any idea on this?
推荐答案
尝试@RequestBody更换@RequestParam(文件)(文件)。另请注意,表单数据对象将不会对IE9和旧的工作。
try to replace @RequestParam("file") with @RequestBody("file"). Also note that the form data object won't work for IE9 and older
这篇关于为什么angularJs文件上传失败到后端数据发送到春天控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文