zoukankan      html  css  js  c++  java
  • layui 批量上传文件 + 后台 用servlet3.0接收【我】

    前台代码:

    【主要参照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+"
    成功上传的文件数:"+obj.successful+"
    失败文件数:"+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次】

  • 相关阅读:
    #Leetcode# 219. Contains Duplicate II
    #Leetcode# 203. Remove Linked List Elements
    #Leetcode# 141. Linked List Cycle
    #Leetcode# 128. Longest Consecutive Sequence
    linux——shell解释
    Linux——互联网搜索引擎nbtscan是一个扫描WINDOWS网络NetBIOS信息的小工具
    Linux——网络端口的状态netstat、ifconfig
    连不上网的原因
    jquery基础笔记
    网址收藏
  • 原文地址:https://www.cnblogs.com/libin6505/p/10565374.html
Copyright © 2011-2022 走看看