ali ibrahim
ali ibrahim

Reputation: 95

File upload with angularJS 405 error

I want to make file upload with angularJS and rest API I use the following code but i get 405 error : "Method Not Allowed" and exception: "org.springframework.web.HttpRequestMethodNotSupportedException"

This is the entity

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

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

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

 // getter and setter

this is 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);
    }

this is angularJS controller

 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>

preview

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

header

 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

Upvotes: 1

Views: 2113

Answers (1)

Lev Kuznetsov
Lev Kuznetsov

Reputation: 3728

Remove headers = "'Content-Type': undefined " from the RequestMapping. As you can see from the header you've posted it is set to multipart/form-data which is what I think it should be anyway. Remove the setting from angular as well, I don't think it does anything to set it to undefined.

Upvotes: 2

Related Questions