SpringBoot实现ajax异步上传文件
upload.html
<form enctype="multipart/form-data" id="fileUploadForm" method="post">
<input type="file" id="file" name="file">
<div class="mt-3">
<button type="button" id="uploadbtn" name="uploadbtn" class="btn btn-primary">
提交
</button>
</div>
</form>
upload.js
$("#uploadbtn").click(function(json){
var formData = new FormData(document.getElementById("fileUploadForm"));
$.ajax({
url:'hcontroller/upload',
type:'POST',
data:formData,
contentType:false,
async:false,
cache:false,
processData:false,
success:function (data) {
if(data.result+"" == "true"){
alert("文件提交成功");
$.getJSON("hcontroller/addmiddletable",{uid:uid,hid:hid},function(json){ console.log(json);
});
}
else if(data.result+"" == "false"){
alert("文件提交失败");
}
},
error:function(data){
console.log(data)
if(data.result+"" == "false"){
alert("文件提交失败");
}
}
});
});
controller
@RequestMapping("upload")
public Map fileUpload(@RequestParam MultipartFile file, HttpServletRequest request){
Map map = new HashMap();
boolean rs = false;
if(!file.isEmpty()){
String fileName = System.currentTimeMillis()+file.getOriginalFilename();
String savePath = "C:\\Users\\zsj55\\Desktop\\上传文件";
File dest = new File(savePath+File.separator+fileName);
try {
file.transferTo(dest);
rs = true;
map.put("result",rs);
} catch (IOException e) {
e.printStackTrace();
map.put("result",rs);
}
}
else if (file.isEmpty()){
map.put("result",rs);
}
return map;
}