我正在尝试使用AngularJs和Spring RESTful Web服务实现一个简单的文件上传功能。
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>File Upload Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="js/myuploadfunction.js"></script>
</head>
<body ng-app="myAp">
<h1>File Upload</h1>
<div ng-controller = "myCtrl">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
</body>
</html>
JS
var myApp = angular.module('myAp', []);
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 = "upload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
REST
@RequestMapping(value="/upload", method = RequestMethod.POST)
public @ResponseBody void upload(@RequestBody MultipartFile file) {
System.out.println(file.getName());
}
当我跑步时,我得到了这个 - POST http://localhost:8080/File/upload 404(Not Found)。 我正在关注http://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs以获取脚本参考。对此有何帮助?
答案 0 :(得分:0)
据我记得,我使用MultipartFile作为@RequestParam而不是@RequestBody
并且名称应与<input>
标记的“名称”属性匹配。