layui(文件)上传添加(模拟)进度条,(后台返回数据真实进度条)

说明:文件主要修改upload.js 组件,但不影响用原组件的使用(已测)

代码地址(包含php后台演示部分):https://github.com/shulongfei/demo-manage.git

在线访问:https://shulongfei.github.io/demo-manage/#layui/upload

参考文章:https://www.cnblogs.com/youmingkuang/p/9183528.html;

1、创建监听函数

// 该部分代码主要使用ajax的xhr属性,我copy别人的,自己也不会写,应该不用管。

   var xhrOnProgress=function(fun) {
      xhrOnProgress.onprogress = fun; //绑定监听
       //使用闭包实现监听绑
      return function() {
          //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
          var xhr = $.ajaxSettings.xhr();
           //判断监听函数是否为函数
            if (typeof xhrOnProgress.onprogress !== 'function')
                 return xhr;
             //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
              if (xhrOnProgress.onprogress && xhr.upload) {
                    xhr.upload.onprogress = xhrOnProgress.onprogress;
              }
              return xhr;
       }
   };

2、页面上传文件加载

// 看看就行,具体内容demo里面有,缺陷,后台必须根据layui格式返回,可看具体layui文档。
load.render({
  elem: '#test-upload-change'
  ,url: 'up.php'
  ,auto:false
  ,exts: 'zip|rar|7z'
  ,xhr:xhrOnProgress
  ,progress:function(value){//上传进度回调 value进度值
    console.log(value);
    element.progress('demo', value+'%')//设置页面进度条
   }
  ,bindAction: '#test-upload-change-action'
  ,before: function(input){
  //返回的参数item,即为当前的input DOM对象
    layer.load(); //上传loading
      console.log('文件上传中');
  }
  ,done: function(res){
    console.log(res);
    layer.closeAll();
    layer.msg("上传成功");
  }
});


3、更改upload.js. 这里很重要,属于核心内容(也是我唯一和别人改的不同的地方)


    t.ajax({
      url: l.url,
      type: l.method,
      data: r,
      contentType: !1,
      processData: !1,
      dataType: 'json',
      
      xhr: l.xhr ? l.xhr(function(e){//此处为新添加功能
          console.log(e);
          var percent=Math.floor((e.loaded / e.total)*100);//计算百分比
          if(l.progress){
            l.progress(percent);//回调将数值返回
          } 
      }) : undefined,

      headers: l.headers || {},
      success: function (t) {
        i++, d(e, t), u()
      },
      error: function () {
        n++, o.msg('请求上传接口出现异常'), m(e), u()
      }
    })

 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值