Angular Spring文件上传

时间:2016-03-07 19:53:38

标签: java angularjs spring spring-mvc

我正试图点击Spring RestController并获得:

  

o.s.web.servlet.PageNotFound:不支持请求方法'POST'

我相信地图控制器缺少一些东西。

<div class="col-sm-1" style="background-color:#cccccc;" align="center"><span class="file-input btn btn-primary btn-file">Import file<input type="file" onchange="angular.element(this).scope().uploadScriptFile(this.files)"></input></span></div>


    $scope.uploadCtrFile = function(files) {
        console.log(">>>>>>>>>>>>>>>>uploadCtrFile");
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
        console.log(">>>>>>>>>>>>>>>>uploadCtrFile angular.toJson: "
                + angular.toJson(fd, 2));

        $http.post('/rest/uploadCtrFile/', fd,{
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function(fd, status, headers, config) {
            $scope.success = ">>>>>>>>>>>>>>>>uploadCtrFile Success: "+JSON.stringify({data: fd});
            console.log($scope.success);
        })
        .error(function(fd, status, headers, config) {
            $scope.success = ( "failure message: " + JSON.stringify({data: fd}));
            console.log($scope.success);
        });

    };

控制器看起来像......

            @RequestMapping(value = "/uploadCtrFile/", headers = "'Content-Type': 'multipart/form-data'", method = RequestMethod.POST)
            @ResponseBody
            public void uploadCtrFile(MultipartHttpServletRequest request, HttpServletResponse response) {

                Iterator<String> itr=request.getFileNames();

                MultipartFile file=request.getFile(itr.next());

                String fileName=file.getOriginalFilename();
                log.debug(">>>>>>>>>>>>>>>>>>>submitted uploadCtrFile: "+fileName);
        }

前端显示这些消息......

 ">>>>>>>>>>>>>>>>uploadCtrFile angular.toJson: {}" tl1gen.js:607:0
 "failure message: {"data":     {"timestamp":1457380766467,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/rest/uploadCtrFile/"}}"

我错过了什么?

1 个答案:

答案 0 :(得分:2)

您发送undefined作为Content-Type的值,此处为:

headers: {'Content-Type': undefined }

但您的控制器需要Content-Type multipart/form-data值:

@RequestMapping(..., headers = "'Content-Type': 'multipart/form-data'", ...)

您应该在请求中发送正确的Content-Type标头,例如:

headers: {'Content-Type': 'multipart/form-data'}

或从控制器定义中删除headers选项:

@RequestMapping(value = "/uploadCtrFile/", method = RequestMethod.POST)