欢迎您访问我的笔记本站旨在于记录一些平时工作中遇到的一些问题和解决方法,方便查阅,部分内容来源于网络,如有侵权请联系我删除
  • 微信微信
您现在的位置是:首页 > JQuery/Js

Layui多文件上传获取进度回调-[原创]

日期:2020-01-06 17:28:19 作者:tanyi 来源:我的笔记 浏览:2522 次
Layui在最新的2.5.5版本中新增了文件上传进度的回调,这对于上传图片需要制作进度条提供了极大的便利。

默认的回调只针对于单一文件上传,不适用于多文件上传,要支持多文件需要对upload.js做一些简单的修改。首先利用编辑器追踪到upload.js文件(下面这段代码位置),然后开始新增两段代码(有注释的为新增代码)。

layui.each(o, function(e, o) {
                    var r = new FormData;
                    var id=e;//此变量为区分上传单位的id
                    r.append(l.field, o), layui.each(l.data, function(e, t) {
                        t = "function" == typeof t ? t() : t, r.append(e, t)
                    }), t.ajax({
                        url: l.url,
                        type: "post",
                        data: r,
                        contentType: !1,
                        processData: !1,
                        dataType: "json",
                        headers: l.headers || {},
                        success: function(t) {
                            i++, d(e, t), u()
                        },
                        error: function() {
                            n++, a.msg("请求上传接口出现异常"), m(e), u()
                        },
                        xhr: function() {
                            var e = new XMLHttpRequest;
                            return e.upload.addEventListener("progress", function(e) {
                                if (e.lengthComputable) {
                                    e.id=id;//将当前id赋值到e对象,也可新增一参数单独传
                                    /**var k=id;**/单独传
                                    var t = Math.floor(e.loaded / e.total * 100);
                                    "function" == typeof l.progress && l.progress(t, e/*,k*/)
                                }
                            }), e
                        }
                    })
                })

修改完后即可在进度回调函数做对应处理,下面是多文件上传完整代码

<!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>
<style>
    .layui-progress-big{width: 500px}
</style>
<body>

<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>
                <th>操作</th>
            </tr></thead>
            <tbody id="demoList"></tbody>
        </table>
    </div>
    <button type="button" class="layui-btn" id="testListAction">开始上传</button>
</div>
</body>
<script src="/static/jquery-3.2.1.min.js" charset="utf-8"></script>
<script src="/static/layui/layui.js" charset="utf-8"></script>
<script>
    layui.use(['upload','element'], function(){
        var upload = layui.upload;
        var element = layui.element;
        var aa={};
        //多文件列表示例
        var demoListView = $('#demoList')
            ,uploadListIns = upload.render({
            elem: '#testList'
            ,field:'img'
            ,url: ""
            ,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><div class=\"layui-progress layui-progress-big\" lay-showPercent=\"true\" lay-filter='"+index+"'>\n" +
                        "<div class=\"layui-progress-bar layui-bg-blue\" lay-percent='0%' ></div>\n" +
                        "</div></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);
                    element.render();
                });
            }
            ,allDone: function(obj){ //当文件全部被提交后,才触发

            }
            ,progress: function(n,index){
                var percent = n + '%' //获取进度百分比
                element.progress(index.id, percent); //可配合 layui 进度条元素使用
            }
            ,done: function(res, index, upload){
                if(res.code == 0){ //上传成功
                    var tr = demoListView.find('tr#upload-'+ index)
                        ,tds = tr.children();
                    tds.eq(3).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(4).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(3).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(4).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });

    });
</script>

layui2.6.6增加了类似参数,但是该版本对laydate的时间范围选择有所改动很不适应所以还是继续使用2.5.5版本。

很多人改了没效果建议你进入到浏览器设置里面清除浏览器的缓存,强制刷新不会有效果

提交评论
评论列表