javascript\jquery 多文件上传,动态添加元素,动态删除父节点元素
浅绿色为原生JavaScript代码
浅黄色为jQuery代码
html
1 <!DOCTYPE html> 2 <html lang="en" xmlns:th="http://www.thymeleaf.org"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 6 <title>动态添加文件上传列表</title> 7 <link th:href="@{/css/bootstrap.min.css}"rel="stylesheet"> 8 <script th:src="@{/js/jquery-3.5.1.min.js}"></script> 9 </head> 10 <body> 11 <div th:if="${uploadStatus}" style="color:red;" th:text="${uploadStatus}">上传成功</div> 12 <form th:action="@{/mutiUploadFile}" method="post" enctype="multipart/form-data"> 13 <div class="form-group"> 14 <label>动态添加文件上传</label> 15 <input type="button" value="添加文件" onclick="add()"/> 16 <div id="file" class="" th:value="文件上传区域"></div> 17 </div> 18 <input id="submit" type="submit" value="上传" style="display: none;margin-top:10px;"> 19 </form> 20 <script> 21 //动态添加上传按钮 22 function add() { 23 var innerdir="<div>"+ 24 "<input type='file' style='''margin:5px;'name='files'required='required'>"+ 25 "<input type='button' value='删除' onclick='remove(this)'>"+ 26 "</div>" 27 // var oldHttp=document.getElementById("file").innerHTML; 28 // document.getElementById("file").innerHTML=oldHttp+innerdir; 29 // document.getElementById("submit").style.display="block"; 30 $("#file").append(innerdir); 31 $("#submit").css("display","block"); 32 } 33 function remove(obj) { 34 // obj.parentElement.remove(); 35 // if(document.getElementById("file").childElementCount==0){ 36 // document.getElementById("submit").style.display="none"; 37 // } 38 $(obj).parent().remove(); 39 if($("#file div").length==0){ 40 $("#submit").css("display","none"); 41 } 42 } 43 </script> 44 </body> 45 </html>
后端控制器代码:
1 @PostMapping("/mutiUploadFile") 2 public String mutiUploadFiles(MultipartFile[] files,Model model){ 3 for(MultipartFile file:files){ 4 String fileName=file.getOriginalFilename(); 5 fileName=UUID.randomUUID()+"_"+fileName; 6 String dirPath="F:/file/"; 7 File filePath=new File(dirPath); 8 if(!filePath.exists()){ 9 filePath.mkdirs(); 10 } 11 try{ 12 file.transferTo(new File(dirPath+fileName)); 13 model.addAttribute("uploadStatus","上传成功"); 14 } catch (IOException e) { 15 e.printStackTrace(); 16 model.addAttribute("uploadStatus","上传失败"); 17 } 18 } 19 return "mutiUpload"; 20 }


浙公网安备 33010602011771号