前台代碼:
【主要參照layui官方 文件上傳示例 https://www.layui.com/demo/upload.html】
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>layui</title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <link rel="stylesheet" href="//res.layui.com/layui/dist/css/layui.css" media="all"> <!-- 注意:如果你直接復制所有代碼到本地,上述css路徑需要改成你本地的 --> </head> <body> <div class="layui-upload"> <button type="button" class="layui-btn layui-btn-normal" id="testList">選擇多文件</button> <div class="layui-upload-list"> <table class="layui-table"> <thead> <tr><th>文件名</th> <th>大小</th> <th>狀態</th> <th>操作</th> </tr></thead> <tbody id="demoList"></tbody> </table> </div> <button type="button" class="layui-btn" id="testListAction">開始上傳</button> </div> <script src="//res.layui.com/layui/dist/layui.js" charset="utf-8"></script> <!-- 注意:如果你直接復制所有代碼到本地,上述js路徑需要改成你本地的 --> <script> layui.use('upload', function(){ var $ = layui.jquery ,upload = layui.upload; //多文件列表示例 var demoListView = $('#demoList') ,uploadListIns = upload.render({ elem: '#testList' ,url: 'http://127.0.0.1/crmCust-web/BatchSupplementIdentityServlet.do?servletType=batchInFiles' ,data: {myId:3435} //除了文件外的額外參數 ,accept: 'file' ,multiple: true ,auto: false ,bindAction: '#testListAction' ,choose: function(obj){ var files = this.files = obj.pushFile(); //將每次選擇的文件追加到文件隊列 //讀取本地文件 obj.preview(function(index, file, result){ var tr = $(['<tr id="upload-'+ index +'">' ,'<td>'+ file.name +'</td>' ,'<td>'+ (file.size/1014).toFixed(1) +'kb</td>' ,'<td>等待上傳</td>' ,'<td>' ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重傳</button>' ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">刪除</button>' ,'</td>' ,'</tr>'].join('')); //單個重傳 tr.find('.demo-reload').on('click', function(){ obj.upload(index, file); }); //刪除 tr.find('.demo-delete').on('click', function(){ delete files[index]; //刪除對應的文件 tr.remove(); uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免刪除后出現同名文件不可選 }); demoListView.append(tr); }); } ,done: function(res, index, upload){ if(res.code == 0){ //上傳成功 var tr = demoListView.find('tr#upload-'+ index) ,tds = tr.children(); tds.eq(2).html('<span style="color: #5FB878;">上傳成功</span>'); tds.eq(3).html(''); //清空操作 return delete this.files[index]; //刪除文件隊列已經上傳成功的文件 } this.error(index, upload); } ,error: function(index, upload){ var tr = demoListView.find('tr#upload-'+ index) ,tds = tr.children(); tds.eq(2).html('<span style="color: #FF5722;">上傳失敗</span>'); tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //顯示重傳 } ,allDone: function(obj){ //當文件全部被提交后,才觸發 // console.log(obj.total); //得到總文件數 // console.log(obj.successful); //請求成功的文件數 // console.log(obj.aborted); //請求失敗的文件數 alert("得到總文件數:"+obj.total+"\r\n成功上傳的文件數:"+obj.successful+"\r\n失敗文件數:"+obj.aborted); $("#demoList").empty(); } }); }); </script> </body> </html>
后台代碼:
package com.crm.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import net.sf.json.JSONObject; /** * * @Package com.crm.servlet * @ * @author * @date 2018年4月2日 上午8:06:15 * @Description: 批量上傳 * @version V1.0 */ @WebServlet("/BatchSupplementIdentityServlet.do") @MultipartConfig public class BatchSupplementIdentityServlet extends AbstractBaseServlet { private static final long serialVersionUID = 1L; private SelectBoxContainer selectBox = new SelectBoxContainer(); public BatchSupplementIdentityServlet() { super(); } @SuppressWarnings({ "rawtypes", "unchecked" }) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext()); WebContextUtils.setWebApplicationContext(context); response.setCharacterEncoding("UTF-8"); Map requestMap = BaseServletHelper.parseRequst2Map(request); HttpSession session = request.getSession(); Map<String,Object> userMap = RedisSessionUtil.getInstance(request).get(session.getId()); // 接收文件 if ("batchInFiles".equals(requestMap.get("servletType")) ) { //獲取額外參數 String myId = request.getParameter("myId"); System.out.println(myId); File path = new File("d:\\tmp"); if (!path.exists()){ path.mkdir(); } /* //根據名稱獲取文件 Part img = request.getPart("file"); //文件全路徑 String filePath = path.getPath() + File.separator + img.getSubmittedFileName(); //寫入文件 img.write(filePath); //輸出信息 System.out.println("File Upload : " + filePath);*/ //獲取文件(不知道文件名稱,獲取所有文件) Collection<Part> parts = request.getParts(); String fileName = null; //遍歷取出文件 for (Part part : parts) { System.out.println("-----------------------"); if(part.getHeader("Content-Disposition").contains("filename")){ fileName = part.getHeader("Content-Disposition"); fileName = fileName.substring(fileName.indexOf("filename=\"")+10, fileName.lastIndexOf("\"")); System.out.println("fileName: "+fileName); //存儲文件 利用part的api將臨時文件寫入目標文件 part.write("d:/tmp/"+fileName); } System.out.println("-----------------------"); } //定義返回map Map<String,Object> reMap = new HashMap<>(); reMap.put("code", 0); reMap.put("filePath", "d:/tmp/"+fileName); //轉換為json返回前台 String result = JSONObject.fromObject(reMap).toString(); PrintWriter out = response.getWriter(); out.println(result); out.flush(); out.close(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
【layui的文件批量上傳,基本都是一個文件請求一次后台,這個也是一樣的,如果你選了3個文件,那么就會向后台請求3次】