我试图向服务器发送帖子,但我总是收到错误 415 我尝试过多次播放但没有任何内容。
JS:
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
method: "POST",
url: "./signup",
data: formData,
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
success : function(data) {
//...
},
error : function(qXHR, textStatus, errorThrown){
console.log(errorThrown, "Error " + qXHR.status);
}
});
HTML:
<form id="signup-form" action="#">
<div class="form-group">
<label>First Name</label>
<input name="firstName" type="text" id="firstName">
</div>
<div class="form-group">
<label>Surname</label>
<input name="surname" type="text" id="surname">
</div>
<div class="form-group">
<label>File</label>
<input type="file" name="attachFile" id="attachFile">
</div>
</div>
<input type="submit" id="btn-submit-signup value="Submit">
</form>
的java
//controller header
@RequestMapping(value = "/signup", headers = "content-type=multipart/*", method = RequestMethod.POST)
public @ResponseBody Response<String> signup(@RequestBody UserSignup details)
//UserSignup
public class UserSignup {
private String firstName;
private String surname;
private MultipartFile attachFile;
public UserSignup(){}
//getters and setters...
}
知道出了什么问题吗?
答案 0 :(得分:0)
Spring提供了有关如何正确处理文件上传的指南:https://spring.io/guides/gs/uploading-files/
摘自指南,这是一个简单的例子
控制器
@Controller
public class FileUploadController {
@PostMapping("/signup")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "redirect:/";
}
}
表格
<form id="signup-form" method="POST" enctype="multipart/form-data" action="/">
<table>
<tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
<tr><td></td><td><input type="submit" value="Upload" /></td></tr>
</table>
</form>
的Ajax
$.post("./signup", $("#signup-form").serialize());