input 多次选择文件批量上传

效果图

效果图

代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0,viewport-fit=cover">
    <title>文件上传</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: 20px;">
    <div id="fileDiv" style="display: none"></div>
    <div>
        <button type="button" id="selectFileBtn">选择文件</button>
        <button type="button" id="uploadActionBtn">开始上传</button>
        <div style="max-width: 1000px;">
            <table border="1">
                <colgroup>
                    <col width="150">
                    <col width="100">
                    <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>
</div>
<script type="text/javascript">
    //模拟已有数据
    function initDataList() {
        for (let i = 0; i < 3; i++) {
            var file = {};
            file.id = i;
            file.name = "文件名" + i;
            file.size = (i + 1) * 100 * 1014;

            var tr = $(['<tr id="upload-done' + file.id + '" data-fileid="' + file.id + '" >'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                , '<td><span>已上传 </span></td>'
                , '<td>'
                , '<button  name="fileDelete" >删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            $("#demoList").append(tr);
        }
        $('button[name="fileDelete"]').off('click').on('click', function (e) {
            var tr = $(this).parent().parent("tr");
            tr.remove();

            var val = $(tr).attr("id");
            val = (val + "").split("-")[1];//
            $("#uploaderInput-" + val).remove();
        });
    }

    initDataList();


    var fileTotalCount = 0;//用于记录文件
    //选择文件
    $("#selectFileBtn").on("click", function (e1) {
        //没有选择文件的情况
        if ($("#uploaderInput").length > 0) {
            $("#uploaderInput").click();
        } else {
            var uploadFile = '<input name="files" id="uploaderInput"  type="file" accept="image/png, image/jpeg, image/gif" />';
            $("#fileDiv").append($(uploadFile));
            $("#uploaderInput").off('change').on('change', function (e) {
                var files = e.target.files;
                var fileNum = files.length;
                if (fileNum > 0) {
                    preview(files);
                    //修改id,加上编号
                    $(this).attr("id", "uploaderInput-" + fileTotalCount);
                }
            });
            $("#uploaderInput").click();
        }

    });

    //上传文件按钮
    $("#uploadActionBtn").on("click", function (e) {
        var filesInputs = $("input[name='files']");
        for (let i = 0; i < filesInputs.length; i++) {
            let fileInput = filesInputs[i];
            let fileid = $(fileInput).data("fileid");
            if (fileid) { //有文件id表示已上传,不重复传
                continue;
            }

            let index = ($(fileInput).attr("id") + "-").split("-")[1];


            var length = fileInput.files.length;
            for (let j = 0; j < length; j++) {
                var file = fileInput.files[j];

                uploadFile(file, {
                    before: function () {
                        console.log("before");
                    },
                    done: function (res) {
                        if (res.code == 0) {
                            $(fileInput).attr("data-fileid", res.data.id);
                            $("tr#upload-" + index).attr("data-fileid", res.data.id);
                        }
                    },
                    progress: function (n) {

                        $("#progress-demo-"+index).text(n+"%")
                        // console.log("progress === "+n);
                    },
                    error: function (err) {
                        console.log("error === " + n);
                    },
                });
            }


        }


    });


    //上传单个文件
    function uploadFile(file, callback) {

        if (callback) callback.before();

        var progressRate = 0;
        var t =setInterval(function () {
            if (callback) callback.progress(++progressRate);
            if(progressRate>=100){
                clearInterval(t);
                var res = {};
                res.code = 0;
                res.data = {
                    id: uuid(5, 16)//文件id
                };
                if (callback) callback.done(res);
            }

        },100);

        // var formData = new FormData();
        // formData.append("files", file);
        // $.ajax({
        //     url: 'https://httpbin.org/post',
        //     type: 'POST',
        //     cache: false,
        //     processData: false,
        //     contentType: false,
        //     data: formData,
        //     xhr: function () {
        //         var xhr = new XMLHttpRequest();
        //         //使用XMLHttpRequest.upload监听上传过程,注册progress事件,打印回调函数中的event事件
        //         xhr.upload.addEventListener('progress', function (e) {
        //             //loaded代表上传了多少
        //             //total代表总数为多少
        //             var progressRate = (e.loaded / e.total) * 100;
        //
        //             //通过设置进度条的宽度达到效果
        //             if (callback) callback.progress(progressRate);
        //         });
        //
        //         return xhr;
        //     },
        //     success: function (res) {
        //
        //         if (callback) callback.done(res);
        //     },
        //     error: function (err) {
        //         if (callback) callback.error(err);
        //     }
        // });
    }


    function preview(files) {
        var fileNum = files.length;
        if (fileNum > 0) {
            for (let i = 0; i < fileNum; i++) {
                let file = files[i];
                let fileName = file.name;

                fileTotalCount++;
                var tr = $(['<tr id="upload-' + fileTotalCount + '"  >'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                    , '<td><span id="progress-demo-' + fileTotalCount + '"> </span></td>'
                    , '<td>'
                    , '<button  name="fileDelete" >删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                $("#demoList").append(tr);
            }
            $('button[name="fileDelete"]').off('click').on('click', function (e) {
                var tr = $(this).parent().parent("tr");
                tr.remove();

                var val = $(tr).attr("id");
                val = (val + "").split("-")[1];//
                $("#uploaderInput-" + val).remove();
            });
        } else {

        }

    }

    //模拟生成文件id
    function uuid(len, radix) {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [], i;
        radix = radix || chars.length;

        if (len) {
            // Compact form
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join('');
    }
</script>
</body>


</html>

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容