为什么angularJs文件上传无法将数据发送到后端的弹簧控制器?

时间:2015-11-06 09:23:20

标签: java angularjs spring spring-mvc

我尝试从前端上传文件以保存在数据库中。但Spring控制器无法接收文件。

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);
            };
         }]);

Spring Controller

@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> 

无法访问Spring控制器。对此有何想法?

1 个答案:

答案 0 :(得分:0)

尝试用@RequestBody替换@RequestParam(&#34; file&#34;)(&#34; file&#34;)。另请注意,表单数据对象不适用于IE9及更早版本