异步请求,原生js代码和jquery方法,文件上传
浅绿色为原生js代码
淡黄色为jQuery封装的函数
$.ajax({ method: 'post', url: '/ajaxUploadFile', data: form, processData: false, contentType: false, success: function (res) { alert(res.msg); }, error: function () { console.log("ajax请求失败"); } });
method:请求方法
url:请求地址
data:请求数据
success:请求成功调用的函数
error:请求失败调用的函数
.html
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>异步无刷文件上传</title> <link th:href="@{/css/bootstrap.min.css}"rel="stylesheet"> <script th:src="@{/js/jquery-3.5.1.min.js}"></script> </head> <body> <form id="form"> <div class="form-group"> <label>异步无刷文件上传</label> <input type="button" value="添加文件" onclick="add()"/> <div id="file" class="" th:value="文件上传区域"></div> </div> <input id="submit" type="button" value="上传" onclick="ajaxUpload()" style="display: none;margin-top:10px;"> </form> <script> function ajaxUpload() { var form=new FormData(); //获取选择的文件 $.each($('input[name="files"]'),function(index,item){ form.append("files",item.files[0]) }); // var xhr=new XMLHttpRequest(); // xhr.open('post','/ajaxUploadFile'); // xhr.send(form); // xhr.onload=function (ev) { // if(xhr.status==200){ // alert(JSON.parse(xhr.responseText).msg); // } // else{ // console.log("ajax请求失败"); // } // } $.ajax({ method: 'post', url: '/ajaxUploadFile', data: form, processData: false, contentType: false, success: function (res) { alert(res.msg); }, error: function () { console.log("ajax请求失败"); } }); } //动态添加上传按钮 function add() { var innerdir="<div>"+ "<input type='file' style='margin:5px;' name='files' required='required'>"+ "<input type='button' value='删除' onclick='remove(this)'>"+ "</div>" document.getElementById("submit").style.display="block"; $("#file").append(innerdir); $("#submit").css("display","block"); } function remove(obj) { $(obj).parent().remove(); if($("#file div").length==0){ $("#submit").css("display","none"); } } </script> </body> </html>
springboot的控制层代码
1 @ResponseBody 2 @PostMapping("/ajaxUploadFile") 3 public Map ajaxUploadFile(MultipartFile[] files){ 4 Map<String,Object> map=new HashMap<>(); 5 map.put("test","test"); 6 for(MultipartFile file:files){ 7 String fileName=file.getOriginalFilename(); 8 fileName=UUID.randomUUID()+"_"+fileName; 9 String dirPath="F:/file/"; 10 File filePath=new File(dirPath); 11 if(!filePath.exists()){ 12 filePath.mkdirs(); 13 } 14 try{ 15 file.transferTo(new File(dirPath+fileName)); 16 map.put("msg","上传成功"); 17 } catch (Exception e) { 18 e.printStackTrace(); 19 map.put("msg","上传失败"); 20 } 21 } 22 return map; 23 }
运行结果: