AngularJS 通过 Spring Restful 上传文件
总结一下,在写下这些文字之前心里很不爽,一个小问题倒腾了这么久...
JS 端:
// 指令 app.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]); }) }) } } }])
// Service app.service('fileUpload', ['$http', function($http) { this.uploadFile = function(file, url) { var fd = new FormData(); fd.append('name', file.name); fd.append('file', file); $http.post(url, fd, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }) .success(function(data, status) { }) .error(function(data, status) { }) } }])
// Controller app.controller('FileUploadModalCtrl', ['$scope', '$uibModalInstance', 'fileUpload', function($scope, $uibModalInstance, fileUpload) { $scope.ok = function() { var file = $scope.modelFile; console.log('file is ' + file); var uploadUrl = './api/file/upload'; fileUpload.uploadFile(file, uploadUrl); $uibModalInstance.close($scope.items); }; $scope.cancel = function() { $uibModalInstance.dismiss('cancel'); } }]).controller('UploadCtrl', function($scope, $uibModalInstance, modelSrc, imgSrc) { $scope.model_src = modelSrc; $scope.img_src = imgSrc; });
<!-- HTML -->
<div class="form-group"> <label for="inputFile">File Input</label> <input type="file" file-model="modelFile"> </div>
Spring 端
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController @RequestMapping("file") public class FileUploadService { @RequestMapping(method = RequestMethod.POST, value = "/upload") public String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { // todo what you want } }
<!-- 这个千万别忘了,在spring配置文件里声明 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
注释就不加了,下班了 :)