带有SpringMVC框架的jQuery Ajax文件上传返回415

我只想做一个用户注册。 这是我的jsp表单(使用引导程序):

<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>

这是我的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);
    }
  })
})  

还有我的springMVC控制器:

@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;
    }
}

如我所说,当我按下“立即注册”按钮时,我得到了415(不受支持的媒体类型)。 请帮忙。

评论