首页 前端知识 2.jquery layui多文件上传回显编辑

2.jquery layui多文件上传回显编辑

2024-06-05 13:06:58 前端知识 前端哥 786 203 我要收藏

一、多文件上传

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增工作汇报')" />
    <!-- 文件上传需要引入layui.css跟layui.js -->
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css" />
    <style>
        .note-editor{height: 300px !important}
        .note-editable{height: 210px;}

        /* 文件上传css */
        tr td {
                position: relative;
            }
        
            .box1 {
                float: left;
            }
        
            .box2 {
                float: right;
                /* display: none; */
            }
        
            .box3 {
                position: absolute;
                left: 0;
                bottom: 0;
                width: 100%;
            }
        
            .demo-delete {
                height: 22px;
                width: 22px;
                border-radius: 50%;
                text-align: center;
                line-height: 100%;
                border: 0;
                background-color: #008000;
                color: #FFFFFF;
            }
        
            .span2 {
                display: none;
        
            }
        
            /* .demo-delete:hover{
            background-color: gray;
        } */
            td:hover .demo-delete {
                background-color: gray;
            }
        
            tr:hover .span1 {
                display: none;
            }
        
            tr:hover .span2 {
                display: block;
            }
        
            #testListAction {
                /* display: none; */
            }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-report-add">
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报日期:</label>
                <div class="col-sm-8">
                    <input type="text" class="time-input form-control" placeholder="请选择汇报日期" name="reportDate" required readonly/>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报人:</label>
                <div class="col-sm-8">
                    <input name="reporter" class="form-control" th:value="${reporter}" type="text" required maxlength="20">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报对象:</label>
                <div class="col-sm-8">
                    <input name="reportTo" class="form-control" type="text" required maxlength="20">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">汇报类型:</label>
                <div class="col-sm-8">
                    <select name="reportType" class="form-control m-b" th:with="type=${@dict.getType('team_report_type')}">
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>

            <!-- 文件编辑上传html部分 -->
            <div class="form-group">
                <label class="col-sm-3 control-label is-required">汇报内容:</label>
                <div class="col-sm-8" style="height: 300px !important;">
                    <input type="hidden" class="form-control" name="reportContent">
                    <div class="summernote" id="reportContent" style="height: 300px !important;"></div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">汇报文件:</label>
                <div class="layui-upload-list col-sm-8">
                    <div class="layui-upload">
                        <div align="left">
                            <button type="button" class="layui-btn layui-btn-normal"  id="testList">选择多文件
                            </button>


                            <input name="reportFileurl" class="filess layui-input" value="" type="hidden">
                        </div>


                    </div>
                </div>
            </div>
            <div class="form-group">

                <label class="col-sm-3 control-label"></label>
                <div class="layui-upload-list col-sm-8">
                    <table class="layui-table" style="margin: 0 0 0 0" cellspacing="0">
                        <tbody id="demoList">

                        </tbody>
                    </table>
                </div>
            </div>

            <div class="form-group">
                <label class="col-sm-3 control-label">备注:</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="500"></textarea>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: summernote-js" />
    <script th:inline="javascript">

    // 文件上传js部分
        layui.use(["jquery", "upload", "form", "layer", "element"], function() {
            var $ = layui.$,
                    element = layui.element,
                    layer = layui.layer,
                    upload = layui.upload,
                    form = layui.form;
            
            var navArr = []; //定义一个数组 用于存储 传过来的 上传文件的路径
            //多文件列表示例
            var demoListView = $('#demoList'),
                uploadListIns = upload.render({
                    elem: '#testList',
                    url: '/common/upload1',
                    progress: function(n, elem, res, index) { //layui2.5.5新增
                        var percent = n + '%' //获取进度百分比
                        element.progress('demo', percent); //可配合 layui 进度条元素使用
        
                        // console.log(elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
                        // console.log(res); //得到 progress 响应信息
                        // console.log(index); //得到当前上传文件的索引,多文件上传时的进度条控制,如:
                        element.progress('demo-' + index, n + '%'); //进度条
                    },
                    accept: 'file',
                    multiple: true,
                    auto: true //选择文件后自动上传
                        ,
                    // bindAction: '#testListAction' //指向一个按钮触发上传
                    //     ,
                    choose: function(obj) {
                        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function(index, file, result) {
                            var tr = $(`<tr id="upload-${index}">
                <td ><div class="box1">
                    <span>${file.name}  </span><span>  ${(file.size / 1014).toFixed(1)}kb</span>
                </div>
                <div class="box3" id="progress-${index}"><div class="layui-progress layui-progress-small" lay-filter="demo-${index}" lay-showPercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div></div>
                <div class="box2"><button class=" layui-btn-xs  demo-delete"><span class="span1">√</span><span class="span2">×</span></button></div>
                </td>
            </tr>`);
        
                            //删除
                            tr.find('.demo-delete').on('click', function() {
                                delete files[index]; //删除对应的文件
                                delete navArr[index.charAt(index.length - 1)]//删除文件名地址在数组中对应的部分
                                $(".filess").val(JSON.stringify(navArr)); //写入form表单的inpu中,一起传过去
                                tr.remove();//删除前端显示tr部分
                                // console.log(index,navArr)
                                uploadListIns.config.elem.next()[0].value =
                                    ''; //清空 input file 值,以免删除后出现同名文件不可选
        
                            });
        
                            demoListView.append(tr);
                        });
                    },
                    done: function(res, index, upload) {
                        
        
                        if (res.code == 0) { //上传成功
                            let  fileObj=[]
                            fileObj[0]=res.filename
                            fileObj[1]=res.fileName
                            
                        
                            // navArr[]上面外面定义空数组
                            navArr.push(fileObj); //返回的文件地址 存进数组
                            
                            $(".filess").val(JSON.stringify(navArr)); //写入form表单的inpu中,一起传过去
                            var tr = demoListView.find('tr#upload-' + index),
                                tds = tr.children();
                            // tr.find('.span1').css('display','block')
                            $(`#progress-${index}`).html(' ') 
                            {
                                // tds.eq(3).html(''); //清空操作#}
                                return delete this.files[index]; //删除文件队列已经完成上传的文件
                            }
                            
                            this.error(index, upload);
                            
                        }
                    }
                });
        })
        
        
        var prefix = ctx + "team/report"
        $("#form-report-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/add", $('#form-report-add').serialize());
            }
        }

        // $("input[name='reportDate']").datetimepicker({
        //     format: "yyyy-mm-dd",
        //     minView: "month",
        //     autoclose: true
        // });

        $(".file-upload").fileinput({
            uploadUrl: ctx + 'common/upload',
            maxFileCount: 1,
            autoReplace: true
        }).on('fileuploaded', function (event, data, previewId, index) {
            $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
        }).on('fileremoved', function (event, id, index) {
            $("input[name='" + event.currentTarget.id + "']").val('')
        })

        $(function() {
            $('.summernote').summernote({
                lang: 'zh-CN',
                dialogsInBody: true,
                callbacks: {
                    onChange: function(contents, $edittable) {
                        $("input[name='" + this.id + "']").val(contents);
                    },
                    onImageUpload: function(files) {
                        var obj = this;
                        var data = new FormData();
                        data.append("file", files[0]);
                        $.ajax({
                            type: "post",
                            url: ctx + "common/upload",
                            data: data,
                            cache: false,
                            contentType: false,
                            processData: false,
                            dataType: 'json',
                            success: function(result) {
                                if (result.code == web_status.SUCCESS) {
                                    $('#' + obj.id).summernote('insertImage', result.url);
                                } else {
                                    $.modal.alertError(result.msg);
                                }
                            },
                            error: function(error) {
                                $.modal.alertWarning("图片上传失败。");
                            }
                        });
                    }
                }
            });
        });
    </script>
</body>
</html>

二、多文件回显编辑再上传

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改工作汇报')" />
    <!-- 文件编辑需要引入layui.css跟layui.js -->
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: bootstrap-fileinput-css"/>
    <th:block th:include="include :: summernote-css" />
    <style>
        .note-editor{min-height: 300px !important}
        .note-editable{min-height: 210px;}
        
        /* 文件上传编辑css */
        tr td {
                position: relative;
            }
        
            .box1 {
                float: left;
            }
        
            .box2 {
                float: right;
                /* display: none; */
            }
        
            .box3 {
                position: absolute;
                left: 0;
                bottom: 0;
                width: 100%;
            }
        
            .demo-delete {
                height: 22px;
                width: 22px;
                border-radius: 50%;
                text-align: center;
                line-height: 100%;
                border: 0;
                background-color: #008000;
                color: #FFFFFF;
            }
            .demo-delete1 {
                height: 22px;
                width: 22px;
                border-radius: 50%;
                text-align: center;
                line-height: 100%;
                border: 0;
                background-color: #008000;
                color: #FFFFFF;
            }
        
            .span2 {
                display: none;
        
            }
        
            
            td:hover .demo-delete {
                background-color: gray;
            }
        
            tr:hover .span1 {
                display: none;
            }
        
            tr:hover .span2 {
                display: block;
            }
        
            .fileMsg {
                text-decoration: underline;
                color: #005CC5;
            }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-report-edit" th:object="${teamWorkReport}">
            <input name="id" th:field="*{id}" type="hidden">
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报日期:</label>
                <div class="col-sm-8">
                    <input type="text" class="time-input form-control" th:field="*{reportDate}" placeholder="请选择汇报日期" name="reportDate" readonly required/>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报人:</label>
                <div class="col-sm-8">
                    <input name="reporter" th:field="*{reporter}" class="form-control" type="text" maxlength="20" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报对象:</label>
                <div class="col-sm-8">
                    <input name="reportTo" th:field="*{reportTo}" class="form-control" type="text" maxlength="20" required>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">汇报类型:</label>
                <div class="col-sm-8">
                    <select name="reportType" class="form-control m-b" th:with="type=${@dict.getType('team_report_type')}">
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}" th:field="*{reportType}"></option>
                    </select>
                </div>
            </div>
            
            <!-- 文件编辑上传html部分 -->
            <div class="form-group">    
                <label class="col-sm-3 control-label is-required">汇报内容:</label>
                <div class="col-sm-8">
                    <input type="hidden" class="form-control" th:field="*{reportContent}">
                    <div class="summernote" id="reportContent" ></div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">汇报文件:</label>
                <div class="layui-upload-list col-sm-8">
                    <div class="layui-upload">
                        <div align="left">
                            <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件
                            </button>
                            
                            <input name="reportFileurl" class="filess layui-input" value="" type="hidden" th:field="*{reportFileurl}">
                        </div>
                        
                        
                    </div>
                    
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label"></label>
                <div class="layui-upload-list col-sm-8">
                    <table class="layui-table" style="margin: 0 0 0 0" cellspacing="0">
                        <tbody id="demoList">
                            
                        </tbody>
                    </table>
                
                </div>
            </div>
           
            <div class="form-group">
                <label class="col-sm-3 control-label">备注:</label>
                <div class="col-sm-8">
                    <textarea name="remark" class="form-control" maxlength="500">[[*{remark}]]</textarea>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: bootstrap-fileinput-js"/>
    <th:block th:include="include :: summernote-js" />
    <script th:inline="javascript">
    
    // 文件上传js部分
    var demoListView = $('#demoList')
    var navArr1 = []; //老的存储文件数组
    var navArr = []; //定义一个数组 用于存储 传过来的 上传文件的路径
        layui.use(["jquery", "upload", "form", "layer", "element"], function() {
            var $ = layui.$,
                    element = layui.element,
                    layer = layui.layer,
                    upload = layui.upload,
                    form = layui.form;
            
            
            //多文件列表示例
            var uploadListIns = upload.render({
                    elem: '#testList',
                    url: '/common/upload1',
                    progress: function(n, elem, res, index) { //layui2.5.5新增
                        var percent = n + '%' //获取进度百分比
                        element.progress('demo', percent); //可配合 layui 进度条元素使用
        
                        // console.log(elem); //得到当前触发的元素 DOM 对象。可通过该元素定义的属性值匹配到对应的进度条。
                        // console.log(res); //得到 progress 响应信息
                        // console.log(index); //得到当前上传文件的索引,多文件上传时的进度条控制,如:
                        element.progress('demo-' + index, n + '%'); //进度条
                    },
                    accept: 'file',
                    multiple: true,
                    auto: true //选择文件后自动上传
                        ,
                    // bindAction: '#testListAction' //指向一个按钮触发上传
                    //     ,
                    choose: function(obj) {
                        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                        //读取本地文件
                        obj.preview(function(index, file, result) {
                            var tr = $(`<tr id="upload-${index}">
                <td ><div class="box1 fileMsg">
                    <span >${file.name}  </span><span>  ${(file.size / 1014).toFixed(1)}kb</span>
                </div>
                <div class="box3" id="progress-${index}"><div class="layui-progress layui-progress-small" lay-filter="demo-${index}" lay-showPercent="true"><div class="layui-progress-bar" lay-percent="0%"></div></div></div>
                <div class="box2"><button class=" layui-btn-xs  demo-delete"><span class="span1">√</span><span class="span2">×</span></button></div>
                </td>
            </tr>`);
        
                            //删除
                            tr.find('.demo-delete').on('click', function() {
                                delete files[index]; //删除对应的文件
                                delete navArr[index.charAt(index.length - 1)]//删除文件名地址在数组中对应的部分
                                $(".filess").val(JSON.stringify(navArr.concat(navArr1))); //写入form表单的inpu中,一起传过去
                                tr.remove();//删除前端显示tr部分
                                // console.log(index,"新的删除",navArr)
                                uploadListIns.config.elem.next()[0].value =
                                    ''; //清空 input file 值,以免删除后出现同名文件不可选
        
                            });
                        
        
                            demoListView.append(tr);
                        });
                    },
                    done: function(res, index, upload) {
                        
        
                        if (res.code == 0) { //上传成功
                        //将上传文件的文件名跟服务器路径放进fileObj里面
                            let  fileObj=[]
                            fileObj[0]=res.filename
                            fileObj[1]=res.fileName
                            
                        
                            // navArr[]上面外面定义空数组
                            navArr.push(fileObj); //返回的文件地址 存进数组
                            // console.log("新上传",navArr)
                            
                            $(".filess").val(JSON.stringify(navArr.concat(navArr1))); //写入form表单的inpu中,一起传过去
                            
                            var tr = demoListView.find('tr#upload-' + index),
                                tds = tr.children();
                                //下载
                                tr.find('td').on('click',function(e){
                                    e.stopPropagation()
                                    // console.log(res.fileName)
                                    
                                     let a = document.createElement('a');
                                                // a.preventDefault();
                                                a.href = res.fileName;
                                                a.download = res.fileName;
                                                a.click()
                                
                                })
                            // tr.find('.span1').css('display','block')
                            $(`#progress-${index}`).html(' ') 
                            {
                                // tds.eq(3).html(''); //清空操作#}
                                return delete this.files[index]; //删除文件队列已经完成上传的文件
                            }
                            
                            this.error(index, upload);
                            
                        }
                    }
                });
        })
    
    //文件编辑回显部分
    $(function(){
        navArr1=JSON.parse($('#reportFileurl').val()) 
        //获取到已上传数据放入navArr1中
        navArr1.forEach((item,i)=>{
            if(item!=null){
                // console.log(item)
                var tr1=$(`<tr id="reload-${i}">
                    <td ><div class="box1">
                        <span class="fileMsg">${item[0]}  </span>
                    </div>
                    
                    <div class="box2"><button class=" layui-btn-xs  demo-delete1"><span class="span1">√</span><span class="span2">×</span></button></div>
                    </td>
                </tr>`)
                
                tr1.find('.demo-delete1').on('click',function(){
                    delete navArr1[i]
                    console.log("加载的删除",navArr1)
                    $(".filess").val(JSON.stringify(navArr.concat(navArr1))); //写入form表单的inpu中,一起传过去
                    tr1.remove();
                })
                tr1.find('td').on('click',function(e){
                    e.stopPropagation()
                    // console.log(prefix+item[1])
                     let a = document.createElement('a');
                                // a.preventDefault();
                                a.href = item[1];
                                a.download = item[1];
                                a.click()
                
                })
                demoListView.append(tr1);
            }
            
        })
    })
    
        var prefix = ctx + "team/report";
        $("#form-report-edit").validate({
            focusCleanup: true
        });
        

        function submitHandler() {
            if ($.validate.form()) {
                $.operate.save(prefix + "/edit", $('#form-report-edit').serialize());
            }
        }

        // $("input[name='reportDate']").datetimepicker({
        //     format: "yyyy-mm-dd",
        //     minView: "month",
        //     autoclose: true
        // });

        // $(".file-upload").each(function (i) {
        //     var val = $("input[name='" + this.id + "']").val()
        //     $(this).fileinput({
        //         'uploadUrl': ctx + 'common/upload',
        //         initialPreviewAsData: true,
        //         initialPreview: [val],
        //         maxFileCount: 1,
        //         autoReplace: true
        //     }).on('fileuploaded', function (event, data, previewId, index) {
        //         $("input[name='" + event.currentTarget.id + "']").val(data.response.url)
        //     }).on('fileremoved', function (event, id, index) {
        //         $("input[name='" + event.currentTarget.id + "']").val('')
        //     })
        //     $(this).fileinput('_initFileActions');
        // });

        $(function() {
            $('.summernote').each(function(i) {
                $('#' + this.id).summernote({
                    lang: 'zh-CN',
                    dialogsInBody: true,
                    callbacks: {
                        onChange: function(contents, $edittable) {
                            $("input[name='" + this.id + "']").val(contents);
                        },
                        onImageUpload: function(files) {
                            var obj = this;
                            var data = new FormData();
                            data.append("file", files[0]);
                            $.ajax({
                                type: "post",
                                url: ctx + "common/upload",
                                data: data,
                                cache: false,
                                contentType: false,
                                processData: false,
                                dataType: 'json',
                                success: function(result) {
                                    if (result.code == web_status.SUCCESS) {
                                        $('#' + obj.id).summernote('insertImage', result.url);
                                    } else {
                                        $.modal.alertError(result.msg);
                                    }
                                },
                                error: function(error) {
                                    $.modal.alertWarning("图片上传失败。");
                                }
                            });
                        }
                    }
                });
                var content = $("input[name='" + this.id + "']").val();
                $('#' + this.id).summernote('code', content);
            })
        });
    </script>
</body>
</html>
转载请注明出处或者链接地址:https://www.qianduange.cn//article/10857.html
标签
评论
发布的文章

基于Vue2的ofd文件预览

2024-06-10 11:06:28

网页快速置灰效果

2024-06-10 11:06:17

HTML5 CSS——Day6

2024-06-10 11:06:11

HTML5 CSS3面试题整理

2024-05-05 22:05:21

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!