Controller @Spring :
我的方法存在问题:
我为MultiPartResolver创建了一个bean。解决问题后的理解是,仅当你需要特定类型的文件或非常特定于应用程序的文件时,才定义此bean。尽管我希望对此有更多了解,并希望能从stackoverflow的技术人员那里听到。
当前问题的解决方案:
我会给出我的源代码,
HTML:
<div ng-controller="myCtrl"> <input type="file" file-model="myFile" /> <button ng-click="uploadFile()">upload me</button> </div>
AngularJS:
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.controller('myCtrl', ['$scope', '$http', function($scope, $http){ $scope.uploadFile = function(){ var file = $scope.myFile; var fd = new FormData(); fd.append('file', file); //We can send anything in name parameter, //it is hard coded to abc as it is irrelavant in this case. var uploadUrl = "/upload?name=abc"; $http.post(uploadUrl, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .success(function(){ }) .error(function(){ }); } }]);
spring:
@RequestMapping(value="/upload", method=RequestMethod.POST) public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file){ if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(name))); stream.write(bytes); stream.close(); return "You successfully uploaded " + name + "!"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
@arahant即使发送请求时在请求有效负载中没有看到任何文档base64内容,Angular也会发送MultiPartFile。