ajaxupload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax提交文件</title>
<script src="browser_components/jquery/dist/jquery.min.js"></script>
</head>
<body>
<form id="uploadForm">
<div>
<label>
选择上载文件:
<input type="file" id="imageFile">
</label>
</div>
<button type="submit">提交文件</button>
</form>
</body>
<script src="js/util.js"></script>
<script>
$(function () {
$('#uploadForm').submit(function () {
let files = document.getElementById("imageFile").files;
if (files.length > 0){
let file = files[0];
uploadImage(file);
} else {
alert("没有选择文件");
}
return false;
});
function uploadImage(file) {
let form = new FormData();
form.append("imageFile",file)
$.ajax({
url:'/upload/file',
method: 'POST',
data: form,
contentType: false,
processData: false,
success: function (r) {
console.log(r);
if (r.code === OK){
alert(r.message);
} else {
alert(r.message);
}
}
})
}
});
</script>
</html>
- form.append(“imageFile”,file)参数名必须和controller一致。
systemController.java
@PostMapping("/upload/file")
public R uploadFile(MultipartFile imageFile) throws IOException {
String path = "E:/upload";
File folder = new File(path);
folder.mkdirs();
String filename = imageFile.getOriginalFilename();
File file = new File(folder,filename);
imageFile.transferTo(file);
return R.ok("成功保存文件");
}
|