【问题标题】:Angular Spring file uploadAngular Spring文件上传
【发布时间】:2016-06-21 12:51:19
【问题描述】:

我正在尝试使用 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/"}}"

我错过了什么?

【问题讨论】:

    标签: java angularjs spring spring-mvc


    【解决方案1】:

    你发送undefined作为Content-Type的值,这里:

    headers: {'Content-Type': undefined }
    

    但是您的控制器需要 Content-Typemultipart/form-data 值:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2017-12-30
      • 2020-11-28
      • 2017-11-02
      • 2021-04-07
      • 2019-06-25
      • 2020-04-19
      • 2019-06-25
      • 2021-06-09
      • 2018-04-07
      相关资源
      最近更新 更多