我能够上传文件就好了,我只是想防止重定向。这显然是通过AJAX表单提交完成的,但我仍然最终在控制器中,然后重定向我。
我的控制器:
@RequestMapping(method=RequestMethod.POST)
public void handleFileUpload(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file){
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(name)));
stream.write(bytes);
stream.close();
//return new ModelAndView("redirect:register");
} catch (Exception e) {
//return new ModelAndView("redirect:register");
}
} else {
//return new ModelAndView("redirect:register");
}
}
JSP部分:
<script>
$('fileUploadForm').submit(function (e) {
$.ajax({
url: '${home}upload',
data: $('fileUploadForm').serialize(),
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
e.preventDefault();
});
</script>
<form id ="fileUploadForm" method="POST" action="upload?${_csrf.parameterName}=${_csrf.token}" enctype="multipart/form-data">
File to upload: <input type="file" name="file">
Name:
<input type="text" name="name">
<input type="submit" value="Upload"> Press here to upload the file!
</form>
答案 0 :(得分:1)