我正在尝试将文件上传到我的 J2eE spring 后端。但是,如果我设置了所需的文件,那么它就无法识别,因此我得出结论,这一定是我尝试从前端发送它的方式。HTML 定义:
<form id="filesUploadForm" action="spring/uploadFile" method="post" enctype="multipart/form-data">
<input class="std" id="file" type="file" name="choose">
</form>
Javascript:(由另一个按钮触发)
function uploadFile() {
var url = 'spring/uploadFile';
var formData = $('#filesUploadForm').serialize();
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function() {
console.log('upload complete');
};
xhr.send(formData);
}
如果相关:这里是 Java 代码:
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void uploadFile(@RequestParam(value = "file", required = false) MultipartFile multipartFile) {
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
}