Ad

JQuery Ajax File Upload Return 415 With Springmvc Framework

I simply want to do is make a User Registration. Here is my jsp form (use bootstrap):

<form id="form"  onsubmit="return false;">
   <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username">
    </div>
    <div class="form-group">
        <label for="avatar">Avatar:</label>
        <input type="file" class="form-control-file" id="avatar" name="avatar">
    </div>
    <button type="submit" class="btn btn-primary" id="submit">Register Now</button>
</form>

Then here is my Ajax:

var _url = "<%= request.getContextPath()%>/user";
$("#submit").click(function(e) {
  e.preventDefault();
  var formData = new FormData();
  formData.append("useranme", $("#username").val())
  formData.append("avatar", $("#avatar")[0].files[0])

  $.ajax({
    url: _url,
    type: 'POST',
    dataType: 'json',
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
    }
  })
})  

And my springMVC controller:

@RequestMapping("/user")
@RestController
public class UserController {
   @PostMapping
    public Response register(@RequestBody User user, @RequestParam("avatar") MultipartFile avatar) throws IllegalStateException, IOException {
        String fileName = avatar.getOriginalFilename();
        System.out.println(fileName); // if i get the fileName, then means success...
        // besiness logic...
        Response res = new Response();
        return res;
    }
}

As I said, when I hit the button Register Now, I got a 415(Unsupported Media Type). Please help.

Ad

Answer

I found that it's the problem with @RequestBody, I removed that,then it works.(and another problem is I can not user "avatar" for @RequestParam, I have to change others... I do not know why..)

Ad
source: stackoverflow.com
Ad