文件上传时出现angularJS 405错误

时间:2015-02-03 15:21:04

标签: java angularjs rest spring-mvc

我想使用angularJS和rest API进行文件上传我使用以下代码 但我得到405错误:“方法不允许” 和异常:“org.springframework.web.HttpRequestMethodNotSupportedException”

这是实体

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "file_name")
private String name;

@Column(name = "file")
private byte[] file;

 // getter and setter

这是Rest Controller

 @RequestMapping(value="/newDocument", headers = "'Content-Type': undefined ",   
    method = RequestMethod.POST)
    public void UploadFile(MultipartHttpServletRequest request
         ,HttpServletResponse response) {
        Iterator<String> itr=request.getFileNames();
        MultipartFile file=request.getFile(itr.next());
        String fileName=file.getOriginalFilename();
        System.out.println(fileName);
    }

这是angularJS控制器

 var file=fileInput.value;
    var filename = file.replace(/^.*[\\\/]/, '');
    var title = filename.substr(0, filename.lastIndexOf('.'));
    $("#title").val(title);
    $("#title").focus();
    $scope.document.title=title;
};


 $scope.uploadFile=function(){
        var formData=new FormData();
        formData.append("file",file.files[0]);
        $http.post('/pagingpoc/app/newDocument', formData, {
            transformRequest: function(data, headersGetterFunction) {
                return data;
            },
            headers: { 'Content-Type': undefined }
            }).success(function(data, status) {                       
                alert("Success ... " + status);
            }).error(function(data, status) {
                alert("Error ... " + status);
            });
 };


  <form ng-submit="uploadFile()" 
    class="form-horizontal enctype="multipart/form-data">
<input type="file" name="file" ng-model="document.fileInput" 
   id="file"  onchange="angular.element(this).scope().setTitle(this)" />
<input type="text" class="col-sm-4" ng-model="document.title" id="title" />
<button class="btn btn-primary" type="submit">
     Submit
  </button> 
 </form>

预览

error: "Method Not Allowed"
exception: "org.springframework.web.HttpRequestMethodNotSupportedException"
message: "Request method 'POST' not supported"
status: 405
timestamp: 1422975829262

 Remote Address:[::1]:8080
 Request URL:http://localhost:8080/pagingpoc/app/newDocument
 Request Method:POST
 Status Code:405 Method Not Allowed
 Request Headersview source
 Accept:application/json, text/plain, */*
 Accept-Encoding:gzip, deflate
 Accept-Language:en-US,en;q=0.8,ar;q=0.6
   Connection:keep-alive
   Content-Length:879585
   Content-Type:multipart/form-data; boundary=
       ----  WebKitFormBoundaryZLhEYy6MadlWhBns 
Cookie:JSESSIONID=220CF5CD66E7831F6A788023151BE412;
NG_TRANSLATE_LANG_KEY=%22en%22; tmhDynamicLocale.locale=%22en%22;
SPRING_SECURITY_REMEMBER_ME_COOKIE=
SmJ1dW41dVgwOUhYbDlKUDJsWHVidz09OmdZc1JkS3BjTkJlQXYxejNyN2FsR3c9PQ
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/pagingpoc/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 
(KHTML,  like    Gecko) Chrome/39.0.2171.95 Safari/537.36
 Request Payload
 ------WebKitFormBoundaryZLhEYy6MadlWhBns
 Content-Disposition: form-data; name="file"; filename="Chrysanthemum.jpg"
 Content-Type: image/jpeg
 ------WebKitFormBoundaryZLhEYy6MadlWhBns-- 
 Response Headersview source
 Allow:HEAD, GET
 Content-Type:application/json;charset=UTF-8
 Date:Tue, 03 Feb 2015 15:03:49 GMT
 Server:Apache-Coyote/1.1
 Transfer-Encoding:chunked
 X-Application-Context:application:dev:8080
 X-Application-Context:application:dev:8080

1 个答案:

答案 0 :(得分:2)

headers = "'Content-Type': undefined "移除RequestMapping。正如您在发布的标题中所看到的那样,它被设置为multipart/form-data,这是我认为应该是的。同时从角度中删除设置,我不认为它可以将其设置为未定义。