精华内容
下载资源
问答
  • layui 批量上传

    2018-12-10 15:31:00
    ="../../js/layui/css/layui.css" rel ="stylesheet" type ="text/css" /> < style type ="text/css" > .userheadimg { width : 50px ; height : 50px ; overflow : hidden ; top : 10px ; ...
    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="piclist.aspx.cs" Inherits="XGHUNLIAN.admin.member.piclist" %>
    
    <%@ Import Namespace="XGHUNLIAN.Common" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>会员照片列表</title>
        <link href="../../css/style.css" rel="stylesheet" />
        <script type="text/javascript" src="../../scripts/jquery/jquery-1.10.2.min.js"></script>
        <script src="../../js/layui/layui.all.js" type="text/javascript"></script>
        <link href="../../js/layui/css/layui.css" rel="stylesheet" type="text/css" />
        <style type="text/css">
            .userheadimg
            {
                width: 50px;
                height: 50px;
                overflow: hidden;
                top: 10px;
                left: 10px;
                z-index: 2;
                border-radius: 50px;
                border: #fff solid 1px;
            }
            .piclist
            {
                width: 100%;
                text-align: center;
            }
            .piclist ul
            {
                margin: 10px;
            }
            .piclist ul li
            {
                padding: 5px;
                float: left;
                text-align: center;
                background: #fff;
                border: #eee solid 1px;
            }
            .piclist ul li a
            {
                color: #000;
                text-decoration: none;
            }
            .piclist ul li .memberimg
            {
                width: 200px;
                height: 200px;
                border-radius: 2px;
                overflow: hidden;
            }
            .piclist ul li .del
            {
                width: 32px;
                height: 32px;
                overflow: hidden;
            }
        </style>
    </head>
    <body id="weixin" style="background: #fff;">
        <form id="form1" runat="server">
        <div class="hd">
            <h3>
                会员照片列表</h3>
        </div>
        <div class="bd" style="padding-top: 10px;">
            <div class="content">
                <div class="tab-content">
                    <dl>
                        <dt>头像:</dt>
                        <dd>
                            <asp:Image ID="Imgheadimgurl" runat="server" CssClass="userheadimg" />
                        </dd>
                    </dl>
                    <dl>
                        <dt>UID:</dt>
                        <dd>
                            <asp:Label ID="labId" runat="server"></asp:Label>
                        </dd>
                    </dl>
                    <dl>
                        <dt>OPENID:</dt>
                        <dd>
                            <asp:Label ID="labopenid" runat="server"></asp:Label>
                        </dd>
                    </dl>
                    <dl>
                        <dt>微信昵称:</dt>
                        <dd>
                            <asp:Label ID="labnickname" runat="server"></asp:Label>
                        </dd>
                    </dl>
                    <dl>
                        <dt>真实名称:</dt>
                        <dd>
                            <asp:Label ID="labzsxm" runat="server"></asp:Label>
                        </dd>
                    </dl>
                    <dl>
                        <dt>电话号码:</dt>
                        <dd>
                            <asp:Label ID="labmob" runat="server"></asp:Label>
                        </dd>
                    </dl>
                </div>
                <br />
                <div class="piclist">
                    <ul>
                        <asp:Repeater ID="rptList" runat="server" onitemcommand="Repeater1_ItemCommand">
                            <ItemTemplate>
                                <li>
                                   <%# htmlstr(Eval("imgurl").ToString())%>
                                    <br />
                                    <asp:LinkButton ID="delLinkButton" runat="server" CommandName="del" CommandArgument='<%# Eval("id") %>'><img src="../../image/del_pic.png" class="del" title="删除照片" /></asp:LinkButton>
                                </li>
                            </ItemTemplate>
                            <FooterTemplate>
                                <div style="clear: both;">
                                </div>
                            </FooterTemplate>
                        </asp:Repeater>
                    </ul>
                </div>
            </div>
        </div>
        <div class="layui-upload">
            <button type="button" class="layui-btn layui-btn-normal" id="SelectList">
                选择多文件</button>
            <div class="layui-upload-list">
                <table class="layui-table">
                    <thead>
                        <tr>
                            <th>
                                文件名
                            </th>
                            <th>
                                大小
                            </th>
                            <th>
                                状态
                            </th>
                            <th>
                                操作
                            </th>
                        </tr>
                    </thead>
                    <tbody id="FileList">
                    </tbody>
                </table>
            </div>
            <button type="button" class="layui-btn" id="ListAction">
                开始上传</button>
        </div>
        <div class="ft">
            <div class="content">
                <span class="button_b"><a href="#" onclick="javascript:history.back(-1);">返回上一页</a></span>
            </div>
        </div>
        <div id="outerdiv" style="position: fixed; top: 0; left: 0; background: rgba(0,0,0,0.7);
            z-index: 2; width: 100%; height: 100%; display: none;">
            <div id="innerdiv" style="position: absolute;">
                <img id="bigimg" style="border: 5px solid #fff;" src="" />
            </div>
        </div>
        <asp:HiddenField ID="hidopenid" runat="server" />
        <script type="text/javascript">
    
            $(function () {
                $(".memberimg").click(function () {
                    var _this = $(this); //将当前的pimg元素作为_this传入函数  
                    imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
                });
            });
    
            function imgShow(outerdiv, innerdiv, bigimg, _this) {
                var src = _this.attr("src"); //获取当前点击的pimg元素中的src属性  
                $(bigimg).attr("src", src); //设置#bigimg元素的src属性  
    
                /*获取当前点击图片的真实大小,并显示弹出层及大图*/
                $("<img/>").attr("src", src).load(function () {
                    var windowW = $(window).width(); //获取当前窗口宽度  
                    var windowH = $(window).height(); //获取当前窗口高度  
                    var realWidth = this.width; //获取图片真实宽度  
                    var realHeight = this.height; //获取图片真实高度  
                    var imgWidth, imgHeight;
                    var scale = 0.8; //缩放尺寸,当图片真实宽度和高度大于窗口宽度和高度时进行缩放  
    
                    if (realHeight > windowH * scale) {//判断图片高度  
                        imgHeight = windowH * scale; //如大于窗口高度,图片高度进行缩放  
                        imgWidth = imgHeight / realHeight * realWidth; //等比例缩放宽度  
                        if (imgWidth > windowW * scale) {//如宽度扔大于窗口宽度  
                            imgWidth = windowW * scale; //再对宽度进行缩放  
                        }
                    } else if (realWidth > windowW * scale) {//如图片高度合适,判断图片宽度  
                        imgWidth = windowW * scale; //如大于窗口宽度,图片宽度进行缩放  
                        imgHeight = imgWidth / realWidth * realHeight; //等比例缩放高度  
                    } else {//如果图片真实高度和宽度都符合要求,高宽不变  
                        imgWidth = realWidth;
                        imgHeight = realHeight;
                    }
                    $(bigimg).css("width", imgWidth); //以最终的宽度对图片缩放  
    
                    var w = (windowW - imgWidth) / 2; //计算图片与窗口左边距  
                    var h = (windowH - imgHeight) / 2; //计算图片与窗口上边距  
                    $(innerdiv).css({ "top": h, "left": w }); //设置#innerdiv的top和left属性  
                    $(outerdiv).fadeIn("fast"); //淡入显示#outerdiv及.pimg  
                });
    
                $(outerdiv).click(function () {//再次点击淡出消失弹出层  
                    $(this).fadeOut("fast");
                });
            }
        </script>
        <script>
            layui.use('upload', function () {
                var $ = layui.jquery,
                upload = layui.upload;
                //多文件列表
                var FileListView = $('#FileList'),
                uploadListIns = upload.render({
                    elem: '#SelectList',
                    // url: '/upload/',
                    url: ' ../../tools/UploadFile.ashx?openid=' + $("#hidopenid").val() + '',
                    accept: 'file',
                    multiple: true,
                    auto: false,
                    bindAction: '#ListAction',
                    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 值,以免删除后出现同名文件不可选
                            });
    
                            FileListView.append(tr);
                        });
                    }, done: function (res, index, upload) {
                        if (res.code == 0) { //上传成功
                            var tr = FileListView.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);
                    }, 
                    allDone: function(obj){ //当文件全部被提交后,才触发
                        location.reload();
      },
                    error: function (index, upload) {
                        var tr = FileListView.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'); //显示重传
                    }
                });
            });
        </script>
        </form>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    
    namespace XGHUNLIAN.tools
    {
        /// <summary>
        /// UploadFile 的摘要说明
        /// </summary>
        public class UploadFile : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                //context.Response.ContentType = "text/plain";
                //context.Response.Write("Hello World");
                string shipin = "*.avi *.rmvb *.rm *.asf *.divx *.mpg *.mpeg *.mpe *.wmv *.mp4 *.mkv *.vob";
                string allowExtension =string.Join("|",new string []{ ".jpg", ".jpeg", ".gif", ".bmp", ".png", ".JPG", ".JPEG", ".GIF", ".BMP", ".PNG" });
                if (context.Request.Files.Count > 0)
                {
                    for (int i = 0; i < context.Request.Files.Count; i++)
                    {
                        HttpPostedFile filePost = context.Request.Files[i]; // 获取上传的文件
                        string aFile = filePost.FileName;
                        string aLastName = aFile.Substring(aFile.LastIndexOf(".") + 1, (aFile.Length - aFile.LastIndexOf(".") - 1)); //扩展名
    
                        if (shipin.IndexOf(aLastName) == -1 && allowExtension.IndexOf(aLastName) == -1)
                        {
                            context.Response.Write("{\"code\":\"1\",\"data\":\"\"}");
                            context.Response.End();
                        }
                        string filename = "";
                        string filePath = SaveExcelFile(filePost,ref filename); // 保存文件并获取文件路径
                        BLL.wei_Member bll = new BLL.wei_Member();
    
                        if (bll.AddImgUrl(context.Request.QueryString["openid"], filename))
                        {
                            context.Response.Write("{\"code\":\"0\",\"data\":\"" + filename + "\"}");
                            context.Response.End();
                        }
                        context.Response.Write("{\"code\":\"1\",\"data\":\"\"}");
                        context.Response.End();
                    }
                }
            }
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
            public  string SaveExcelFile(HttpPostedFile file,ref string filename_)
            {
                try
                {
                    var fileName = file.FileName.Insert(file.FileName.LastIndexOf('.'), "-" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                    var filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/Upload/Image"), fileName);
                    string directoryName = Path.GetDirectoryName(filePath);
                    if (!Directory.Exists(directoryName))
                    {
                        Directory.CreateDirectory(directoryName);
                    }
                    file.SaveAs(filePath);
                    filename_ = fileName;
                    return filePath;
                }
                catch
                {
                    return string.Empty;
                }
            }
        }
    }

     

    转载于:https://www.cnblogs.com/muxueyuan/p/10096799.html

    展开全文
  • 代码如下: <!DOCTYPE html> <... ...Layui</title> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name

    代码如下:

    <!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="layui-v2.5.7/layui/css/layui.css"  media="all">
      <script src="layui-v2.5.7/layui/layui.js" type="text/javascript" charset="utf-8"></script>
      <!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
    </head>
    <body>
              
    <blockquote class="layui-elem-quote">通过以下按钮可以上传对应文件到jekins服务器,进行服务器验证</blockquote>   
              
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
      <legend>服务器文件上传列表</legend>
    </fieldset> 
     
    <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>  
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
      <legend>下载对应服务器文件</legend>
    </fieldset> 
    <form class="layui-form" action="">
      <div class="layui-form-item">
         <div class="layui-inline">
           <label class="layui-form-label">搜索选择框</label>
           <div class="layui-input-inline">
             <select name="modules" lay-verify="required" lay-search="" id="csvfilename">
               <!-- <option value="">直接选择或搜索选择</option> -->
             </select>
           </div>
         </div>
    	 <div class="layui-inline">
    	 	    <button type="button" class="layui-btn" id="download">下载文件</button>
    	 </div>
       </div>
    </form>
    
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
      <legend>获取服务器文件更新日期</legend>
    </fieldset> 
    <form class="layui-form" action="">
    <div class="layui-inline">
    	 	    <button type="button" class="layui-btn" id="getDateId">获取日期</button>
    </div>
          <pre class="layui-code" id="filenameid"></pre>
          <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
    </form>
    
    
    <script>
    	
    	
    	
    	
    layui.use('upload', function(){
      var $ = layui.jquery
      ,upload = layui.upload;
      
     
      //多文件列表示例
      var demoListView = $('#demoList')
      ,uploadListIns = upload.render({
        elem: '#testList'
        ,url: 'http://localhost:8889/uploadExcelFile' //改成您自己的上传接口
        ,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/1024).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){
    		console.log(res);
    		// console.log(index);
    		// console.log(upload);
    		
          if(res.message=='上传成功!'){ //上传成功
            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]; //删除文件队列已经上传成功的文件
          }else{
    		  this.error(index, upload);
    	  }
          // 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'); //显示重传
        }
      });
      
      
    });
    
    layui.use(['layer','form', 'layedit', 'laydate'], function(){ 
      var $ = layui.$ //由于layer弹层依赖jQuery,所以可以直接得到
      ,layer = layui.layer;
    	// $.ajaxSetup({async: false});
        $.ajax({
               type: "get",
               url: "http://localhost:8889/getCsvFilename",
               contentType: "application/x-www-form-urlencoded",
               data: {'type':'.csv'},
               success: function (data) {
    				var select = $("#csvfilename");//TypeID为HTML标签ID
    				var csvfilename1=data.filename;
                    for(j = 0,len=csvfilename1.length; j < len; j++) {
    					var filename = csvfilename1[j];
    					filename=filename.substring(0,filename.indexOf('.csv')+4);
    					console.log(filename);
    	       		    $("#csvfilename").append("<option value=\""+filename+"\">"+ filename+"</option>");
    	   		    }
    				
                    layui.form.render("select");
               }
           });
    	   // console.log("csvfilename1:"+csvfilename1);
    	   // 
    
    	function getCsvFilename(){
    	    $.ajax({
    	        type: "get",
    	        url: "http://localhost:8889/getCsvFilename",
    	        contentType: "application/x-www-form-urlencoded",
    	        data: {'type':'.csv'},
    	        success: function (data) {
    	            //实际操作的时候,返回的json对象中可能会有成功错误的判断标记,所以可能也需要判断一下
    	            //JSON.stringify()
    	
    	            $("#filenameid").html(data.filename);
    	
    	        }
    	    });
    	}
       
    	// window.onload=getCsvFilename();
    	
    	
    	function download(){
    		var filename=$("#csvfilename").val();
    		if (filename == "请输入excel文件名"||$.trim(filename) == '') {
    	        alert("请选择下载文件");
    	     return;
    	   }
    		$.ajax({
    	        type: "get",
    	        headers: {
    	        	},
    	        url: "http://localhost:8889/download1",
    	        contentType: "application/x-www-form-urlencoded",
    	        data: {'filename':filename},
    	        success: function (data) {
    	            //实际操作的时候,返回的json对象中可能会有成功错误的判断标记,所以可能也需要判断一下
    	            if(data.status=='1'){
    	            	alert(data.message);
    	            }else{
    					console.log("gohere~~~");
    	            	// window.location.href="http://localhost:8889/download?filename="+filename;
    					window.open("http://localhost:8889/download?filename="+filename);
    	            }
    	            
    	        }
    	    });
    		
    	}
    	
    	
    	$("#download").click(function(){
    		download();
    	});
    	
    	$("#getDateId").click(function(){
    		getCsvFilename();
    	});
    	
    	
    	
    
       
      //……
    });
    
    layui.use(['form', 'layedit', 'laydate'], function(){
      var form = layui.form
      ,layer = layui.layer
      ,layedit = layui.layedit
      ,laydate = layui.laydate;
      
     
      // //表单赋值
      // layui.$('#LAY-component-form-setval').on('click', function(){
      //   form.val('example', {
      //     "username": "贤心" // "name": "value"
      //     ,"password": "123456"
      //     ,"interest": 1
      //     ,"like[write]": true //复选框选中状态
      //     ,"close": true //开关状态
      //     ,"sex": "女"
      //     ,"desc": "我爱 layui"
      //   });
      // });
      
      // //表单取值
      // layui.$('#LAY-component-form-getval').on('click', function(){
      //   var data = form.val('example');
      //   alert(JSON.stringify(data));
      // });
      
    });
    </script>
    
    </body>
    </html>

     

    效果如下:

    展开全文
  • /*** * @Package com.crm.servlet * @ *@author* @date 2018年4月2日 上午8:06:15 * @Description: 批量上传 *@versionV1.0*/@WebServlet("/BatchSupplementIdentityServlet.do") @MultipartConfigpublic class ...

    packagecom.crm.servlet;importjava.io.File;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.Collection;importjava.util.HashMap;importjava.util.Map;importjavax.servlet.ServletException;importjavax.servlet.annotation.MultipartConfig;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjavax.servlet.http.Part;importorg.springframework.context.ApplicationContext;importorg.springframework.web.context.support.WebApplicationContextUtils;importnet.sf.json.JSONObject;/***

    * @Package com.crm.servlet

    * @

    *@author* @date 2018年4月2日 上午8:06:15

    * @Description: 批量上传

    *@versionV1.0*/@WebServlet("/BatchSupplementIdentityServlet.do")

    @MultipartConfigpublic class BatchSupplementIdentityServlet extendsAbstractBaseServlet {private static final long serialVersionUID = 1L;private SelectBoxContainer selectBox = newSelectBoxContainer();publicBatchSupplementIdentityServlet() {super();

    }

    @SuppressWarnings({"rawtypes", "unchecked"})protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {

    ApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

    WebContextUtils.setWebApplicationContext(context);

    response.setCharacterEncoding("UTF-8");

    Map requestMap=BaseServletHelper.parseRequst2Map(request);

    HttpSession session=request.getSession();

    Map 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 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 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) throwsServletException, IOException {

    doGet(request, response);

    }

    }

    展开全文
  • 【主要参照layui官方 文件上传示例 https://www.layui.com/demo/upload.html】 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>layui</title> ...

     

    前台代码:

    【主要参照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次】

     

    转载于:https://www.cnblogs.com/libin6505/p/10565374.html

    展开全文
  • 摘要Laravel 使用 layui 文件上传组件批量上传图片。layui是一款经典国产模块化前端UI框架,首先看看官方的介绍:layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织...
  • php结合layui前端实现多图上传前端html代码请选择图片文件名图片预览大小状态操作开始上传js 代码layui.use('upload', function() {var $ = layui.jquery,upload = layui.upload;//多文件列表示例var demoListView =...
  • HTML文件多文件选择上传文件预览图:php文件0,'msg'=> '','data' =>array('src' => $dir . $_FILES["file"]["name"]),);$file_info = $_FILES['file'];$file_error = $file_info['error'];if (!is_dir($dir...
  • layui+php实现多文件上传的方法发布时间:2020-05-18 15:57:23来源:亿速云阅读:118作者:小新今天小编给大家分享的是layui+php实现多文件上传的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了...
  • Layui文件单个上传、批量上传、多条件上传

    千次阅读 热门讨论 2019-10-31 17:06:10
    Layui超实用10篇技术解决方案:https://blog.csdn.net/libusi001/article/details/100065911 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~...一、文件上传前端 <div> <div class="layui-upload" align="left"> ...
  • 使用layui的文件上传组件,可以方便的弹出文件上传界面。效果如下:点击【批量导入】按钮调用js脚本importData(config)就可以实现数据上传到服务器。脚本:/**** 批量导入* config.downUrl 下载模板url* config....
  • layui 单图片上传 多图片批量上传

    千次阅读 2019-01-22 22:54:07
    //批量多张图片上传 layui.use(['upload', 'element'], function() {  var upload = layui.upload,  element = layui.element; //上传  upload.render({  elem: '#headImgs',  url: '<%=basePath%>/...
  • 今天小编就为大家分享一篇layui 上传文件_批量导入数据UI的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 1、添加LayUI上传组件需要的js文件jquery.min.js、layui.all.js、layer.js2、导入Java上传组件包commons-fileupload、commons-io3、在spring中配置上传文件大小限制<bean id="multipartResolver" class="org....
  • layui 上传文件——批量导入数据UI

    千次阅读 2018-10-17 16:12:41
    使用layui的文件上传组件,可以方便的弹出文件上传界面。 效果如下: 点击【批量导入】按钮调用js脚本importData(config)就可以实现数据上传到服务器。 脚本: /*** * 批量导入 * config.downUrl 下载模板...
  • 最近需要做一个批量上传图片的功能,为丰富前端框架的拓展学习使用,这次打算用layui前端框架实现,源码放在文章底部,废话不多说,先上演示效果 执行前: 操作后: 一、导入对应的layui样式及其资源文件 1.引入...
  • Layui+vue 批量上传图片和显示列表

    千次阅读 2018-12-11 15:46:39
    -- <label class="layui-form-label">批量上传图片</label> -->  <div class="layui-input-block">  <button type="button" class="layui-btn" id="test1">  <i class="layui-icon">选择图片(最多...
  • //页面JS layui.use('upload', function () { var $ = layui.jquery, upload = layui.upload; // 多文件列表示例 var demoListView = $('#demoList') ...
  • 1、目的需求:前台批量上传文件,并在后台进行接收 前台代码:配置URL路径:url: '/KeepElectricty/uploadfiles'其中KeepElectricty是控制器,uploadfiles是接收方法 <!--HTML部分--> <div class=...
  • 关于layui 多文件上传一些问题

    千次阅读 2019-10-14 15:21:49
    最近使用layui文件上传模块实现批量上传图片遇到一些问题,包含:批量上传实时进度条,选中文件总数统计以及上传完成的文件统计。这篇文章主要是总结使用layui上传模块过程中遇到一些问题以及解决思路,这里不对...
  • 一直都在用layui,好处不多说,是因为layui简洁易写,并且后台大多数组件都有,很省事,但最近在工作的时候,发现layui上传组件很让人蛋疼,话不多说,先看问题: 使用layui的多文件上传时,发现layui的实现逻辑是...
  • SSM+Layui实现批量导入数据功能

    千次阅读 多人点赞 2019-05-04 16:26:28
    SSM+Layui实现批量导入数据功能 最近要实现批量导入功能,查看了相关资料,以及百度了相关内容,发现有点不是很全,特别是引入的依赖不全 话不多说,直接上代码开始: 1、pom.xml文件引入相关依赖 <!--文件上传...
  • form class="layui-form" style="padding-top: 2%" lay-filter="goods-image-add"> <div class="layuimini-main"> <input type="hidden" id="files" name="files" value=""> <div class=...
  • 如图所示,通过勾选多选框实现选中,点击批量下载会将数据以Excel的格式批量下载到本地 关于勾选之后是传id数组还是传整个勾选的对象数组,先说结论: 应该传的是id数组而不是对象数组 原因如下: 1. 我们为什么...

空空如也

空空如也

1 2 3 4
收藏数 68
精华内容 27
关键字:

layui批量上传