layui upload阻止文件上传问题,及多选文件上传

本文介绍在使用layui框架进行文件上传时遇到的问题及其解决方案。针对layui版本2.4.5中无法通过before回调阻止文件上传的情况,提供了两种解决办法:升级至最新版本或修改源代码。同时分享了实现多文件上传进度条显示的方法。

1、效果展示: 

2、需求:

        下拉框及月份都为不空,且有文件数据才能提交上传。

3、环境:

        目前项目中引用的 layui 版本是 2.4.5。在 before 中进行判断,使用 return false 想要阻止文件上传没反应,文件仍然会被提交上去。

4、解决方法:

        去翻了一下日志,这个 bug 在 v2.6.7 版本才被修复,因此有两种方式:

1. 方法一:下载 layuiv2.6.8,替换 upload.js;

2. 方法二:修改源代码:

【参考:layui upload 阻止上传_Im灬大神的博客-优快云博客_layui upload阻止上传】:

(1)找到 upload.js 

(2) 打开 “自动换行”,搜索: “ "choose" ”;修改下面画红框部分:

即:将原来的:

y=function(){if("choose"!==t&&!l.auto||(l.choose&&l.choose(g),"choose"!==t))return l.before&&l.before(g),a.ie?a.ie>9?u():c():void u()};

改成下面的:

y=function(){if("choose"!==t&&!l.auto||(l.choose&&l.choose(g),"choose"!==t))return (l.before&&l.before(g))===false?"":a.ie?a.ie>9?u():c():void u()};

5、upload 使用:

<!-- 选择文件 -->
<div class="layui-form-item">
  <div class="layui-inline">
      <label class="layui-form-label"><em class="must">*</em>文件上传:</label>
      <div class="layui-input-inline">          
          <button type="button" class="st-btn" id="testList" style="width: 100px;"><i class="st-icon">&#xe612;</i>&nbsp;&nbsp;选择文件</button>
          <div class="lead-file mrb20">
            <p style="color: #999;">支持拓展名: .xls .xlsx</p>
          </div>
      </div>
  </div>
</div>

<!-- 显示文件 -->
<div class="layui-upload-list" style="max-width: 1000px;">
  <table class="layui-table">
    <colgroup>
      <col>
      <col width="150">
      <col width="260">
      <col width="150">
    </colgroup>
    <thead>
      <tr><th>文件名</th>
      <th>大小</th>
      <th>上传进度</th>
      <th>操作</th>
    </tr></thead>
    <tbody id="demoList"></tbody>
  </table>
</div>

<!-- 文件上传 -->
<div class="layui-form-item" style="padding:20px 0 140px;">
  <div class="layui-input-block">
    <button type="button" class="st-btn-normal mrr20" id="lead">上传</button>
    <button class="st-btn-normal st-btn-cancel" onclick="javascript:window.history.back(); return false;">返回</button>
  </div>
</div>

         注意:提交按钮(这里是 “上传”)最好添加一个 “ type="button" ”,否则点击按钮,表单会自动提交(整个页面也会刷新)。

         下面这部分代码是在 layui 示例中复制过来的,具体可以去官网上看一下案例。

var uploadListIns = upload.render({
  elem: '#testList'
  ,elemList: $('#demoList') //列表元素对象
  ,url: '' //此处用的是第三方的 http 请求演示,实际使用时改成您自己的上传接口即可。
  ,data: {
    yearMon: function(){ return $("#yearMonth").val(); },
    groupId: function(){ return $("#groupId option:selected").val(); }
  }
  ,accept: 'file'
  ,multiple: true
  ,exts: "xls|xlsx|XLS|XLSX"
  ,auto: false
  ,bindAction: '#lead'
  ,before: function(obj){
    console.log("上传之前",Object.keys(this.files).length)
    if($("#groupId option:selected").val()=='' || $("#yearMonth").val()=="" || Object.keys(this.files).length==0){
      layer.confirm('请将数据补充完整', {icon: 0});
      return false;
    } else {
      layer.open({
        type: 1,
        title: false,
        skin: 'upload-tip',
        area: ['416px', '228px'],
        closeBtn: 0,
        shadeClose: false,
        content: '<div class="tip-content"><p class="tip-top"></p><p>文件解析中,请勿关闭页面!</p><img src="../../common/plugins/layui/css/modules/layer/default/loading-0.gif"/></div>'
      });
    }
  }
  ,choose: function(obj){   
    var that = this;
    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><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></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 值,以免删除后出现同名文件不可选
      });
      
      that.elemList.append(tr);
      element.render('progress'); //渲染新加的进度条组件
    });
  }
  ,done: function(res, index, upload){ //成功的回调
    layer.closeAll();
    var that = this;
    if(res.code == dataStatusCode){ //上传成功
      var tr = that.elemList.find('tr#upload-'+ index)
      ,tds = tr.children();
      tds.eq(3).html(''); //清空操作
      delete this.files[index]; //删除文件队列已经上传成功的文件
      successAlert("文件上传成功!");
      return;
    } else if(res.code == invaildCode){
      window.location.href = '../../login.html';
    } else {
      this.error(index, upload);
    }
  }
  ,allDone: function(obj){ //多文件上传完毕后的状态回调
    console.log("多文件上传完毕后",obj)
    // if(obj.successful){
    //   layer.msg(obj.total+"个文件上传成功!")
    // }
  }
  ,error: function(index, upload){ //错误回调
    layer.closeAll();
    layer.msg("上传失败,请联系管理员!",{icon: 2});
    var that = this;
    var tr = that.elemList.find('tr#upload-'+ index)
    ,tds = tr.children();
    tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
  }
  ,progress: function(n, elem, e, index){ //注意:index 参数为 layui 2.6.6 新增
    element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
  }
});

//选择文件判断
$("#lead").click(function(){
  if($("#groupId option:selected").val()=='' || $("#yearMonth").val()==""){
    console.log(1)
    layer.confirm('请将数据补充完整', {icon: 0});
    return false;
  }
})

6、多文件上传进度条不显示

参考 Layui多文件上传进度条 - 马冬梅 - 博客园

关于layui 多文件上传一些问题_Chen DingFeng的博客-优快云博客

其他:

多文件上传时“单个重传”会刷新整个页面: 

<think>好的,用户想用Layui框架实现文件上传,并且限制文件类型和小。我需要根据提供的引用内容来解答这个问题。首先,我要回忆Layui上传组件的基本用法,然后结合用户的需求进行调整。用户提到文件,所以需要设置multiple:true。引用中的代码有提到accept和size参数,这可能对应文件类型和限制。在引用2的代码里,accept设置为"file",但用户可能需要具体的类型比如图片或文档,所以应该替换成对应的MIME类型,比如'file'可以改为'images'或者指定扩展名。例如,accept: 'images'限制图片,或者用acceptMime:'image/*'来指定。文件限制在引用2中用的是size:50*1024,单位是KB,所以用户需要根据自己的需求调整这个数值。比如50*1024是50MB,但可能需要确认单位是否正确,因为Layui的size单位是KB,所以50*1024KB等于50MB,这可能正确。另外,用户需要,所以必须确保upload.render配置中包含multiple:true。引用2中的代码注释掉了//multiple:true,所以需要取消注释或者显式设置为true。然后,需要检查上传按钮的绑定,确保elem指向正确的元素ID,并且bindAction指定触发上传的动作按钮。引用2中的例子用了auto: false,这样择文件后不会自动上传,需要用户点击另一个按钮来触发,这可能符合用户的需求。 最后,测试代码是否正常工作,包括个文件时的显示,以及上传时的类型和限制是否生效。如果有错误,需要检查控制台输出,并确保后端接口正确处理这些限制。 可能还需要在before回调中设置额外的参数,比如引用2中的this.data,用于传递业务ID等数据。用户可能需要类似的功能,所以需要指导如何添加这些参数。总结步骤:配置upload.render,设置multiple:true,accept指定类型,size限制小,并处理上传逻辑。同时提供示例代码,确保用户能复制并修改使用。</think>以下是使用Layui框架实现文件上传限制文件类型和尺寸的配置方法: ### 一、核心配置步骤 1. **文件配置** ```javascript multiple: true //开启文件择 ``` 2. **文件类型限制** ```javascript accept: 'file' //默认所有类型 //可替换为: accept: 'images' //限定图片类型 //或指定扩展名: acceptMime: 'image/*,application/pdf' //限定jpg/png/pdf类型 ``` 3. **文件限制** ```javascript size: 50*1024 //单位KB(此处表示50MB) ``` ### 二、完整实现代码 ```html <div class="layui-upload"> <button type="button" class="layui-btn" id="multiUpload">文件</button> <button type="button" class="layui-btn" id="startUpload">开始上传</button> </div> <script> layui.use('upload', function(){ var upload = layui.upload; // 文件上传实例 upload.render({ elem: '#multiUpload', url: '/your/upload/api', auto: false, //关闭自动上传 multiple: true, //开启 acceptMime: 'image/png,image/jpeg,application/pdf', //限定文件类型 size: 10*1024, //限制10MB bindAction: '#startUpload', //绑定上传按钮 choose: function(obj){ //预览文件列表 var files = this.files = obj.pushFile(); obj.preview(function(index, file, result){ console.log('已择:', file.name); }); }, done: function(res){ console.log('上传完成:', res); } }); }); </script> ``` ### 三、关键参数说明 1. **acceptMime**参数支持以下格式: - `image/*` 所有图片类型 - `application/pdf` 指定PDF文件 - 个类型用逗号分隔 2. **size**计算规则: $$1MB = 1024KB$$ $$size = 文件小(MB) \times 1024$$ 3. **异常处理**建议添加: ```javascript error: function(index, upload){ layer.msg('文件小超过限制或类型不符'); } ``` ### 四、注意事项 1. 服务端需要同步验证文件类型和小,防止前端绕过限制[^2] 2. 进度条功能可通过`progress: function(n, elem, res)`回调实现 3. 建议添加`before`回调进行附加参数传递: ```javascript before: function(obj){ this.data = { businessId: $("#id").val() }; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值