首先看效果图

layui多中类型多个附件上传实现

上传之后效果

layui多中类型多个附件上传实现

修改页面附件上传 删除等功能

layui多中类型多个附件上传实现

layui多中类型多个附件上传实现

请看下边代码实现,新增页面

<div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-header"><strong>原文上传</strong>(只可上传五个原文,支持常用文件格式)
          </div>
          <div class="layui-card-body">
            <div class="layui-upload">
              <button type="button" class="layui-btn layui-btn-normal" id="test-upload-testList">选择多文件</button> 
              <div class="layui-upload-list">
                <table class="layui-table">
                  <thead>
                    <tr><th>文件名</th>
                    <th>大小</th>
                    <th>状态</th>
                    <th>操作</th>
                  </tr></thead>
                  <tbody id="test-upload-demoList"></tbody>
                </table>
              </div>
              <button type="button" class="layui-btn" style="background-color: #1E9FFF;" id="test-upload-testListAction">开始上传</button>
            </div> 
          </div>
        </div>
</div>

js部分

            //多文件列表示例
            var demoListView = $('#test-upload-demoList')
              ,uploadListIns = upload.render({
              elem: '#test-upload-testList'
              ,url: cxt +'fileManage/tHsapDaAttachment/upload'
              ,accept: 'file'
              ,data: {token:token,source:'t_hsap_da_wenshu',daid:id,datype:1} //可选项。额外的参数,如:{id: 123, abc: 'xxx'}
              ,number:5
              ,multiple: true
              ,auto: false
              ,bindAction: '#test-upload-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>'+ (file.size/1014).toFixed(1) +'kb</td>'
                    ,'<td>等待上传</td>'
                    ,'<td>'
                      ,'<button class="layui-btn layui-btn-mini test-upload-demo-reload layui-hide">重传</button>'
                      ,'<button class="layui-btn layui-btn-mini layui-btn-danger test-upload-demo-delete">删除</button>'
                    ,'</td>'
                  ,'</tr>'].join(''));
                  
                  //单个重传
                  tr.find('.test-upload-demo-reload').on('click', function(){
                    obj.upload(index, file);
                  });
                  
                  //删除
                  tr.find('.test-upload-demo-delete').on('click', function(){
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                  });
                  
                  demoListView.append(tr);
                });
              }
              ,done: function(res, index, upload){
                if(res.code == 0){ //上传成功
                  var tr = demoListView.find('tr#upload-'+ index)
                  ,tds = tr.children();
                  tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                  tds.eq(3).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(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.test-upload-demo-reload').removeClass('layui-hide'); //显示重传
              }
            });

后台代码逻辑

public final static String UPLOAD_FILE_PATH = "G:/app-mybatis/fileDownload/";//后期加入到配置文件中

    /**
     * 
     * 简要说明:附件上传工具类
     * 编写者:王云峰
     * 创建时间:2020-09-10
     * @param
     * @return
     * @throws Exception 
     * @throws IllegalStateException 
     */
     @PostMapping(value = "upload")
     @ResponseBody
     public String  uploadDocs(MultipartFile file) throws IllegalStateException, Exception{
        String token=request.getParameter(SystemCons.TOKEN_PARAM);//获取token
        String daid=request.getParameter("daid");//主表id
        String source=request.getParameter("source");//来自哪张表
        String datype=request.getParameter("datype");//什么类型 1文书 2会计 3基建 4设备 5音响 6照片 7实物
        Map<String, Object> uploadData = new HashMap<String, Object>();
        //2020/08/24/T_HSAP_DA_ATTACHMENT_3245839_彭慧芳.jpg
        //先保存数据,然后再上传附件
        String fileName = file.getOriginalFilename();
        String fileType = fileName.split("\\.")!=null && fileName.split("\\.").length==2?fileName.split("\\.")[1]:"";
        THsapDaAttachment tHsapDaAttachment=new THsapDaAttachment();
        String id=RandomUtil.randomUUID();
        tHsapDaAttachment.setId(id);
        tHsapDaAttachment.setDaid(daid);
        tHsapDaAttachment.setAttachname(fileName);
        tHsapDaAttachment.setApptype(fileType);
        tHsapDaAttachment.setDatype(Integer.parseInt(datype));
        tHsapDaAttachment.setCreattime(System.currentTimeMillis());
        String uploadname=DateUtil.thisYear()+"/"+DateUtil.thisMonth()+"/"+DateUtil.thisDayOfMonth()+"/T_HSAP_DA_ATTACHMENT_"+id+"_"+fileName;
        tHsapDaAttachment.setUploadname(uploadname);
        tHsapDaAttachment.setSource(source);
        tHsapDaAttachmentService.insert(tHsapDaAttachment);
        FileOperation.createFolder(UPLOAD_FILE_PATH+DateUtil.thisYear()+"/"+DateUtil.thisMonth()+"/"+DateUtil.thisDayOfMonth());//如果该父级没有文件夹,则循环创建
        //然后保存附件到对应目录下 hutool工具类上传方法 
        File saveFile = new File(UPLOAD_FILE_PATH+uploadname); 
        file.transferTo(saveFile);  //进行写入文件
        uploadData.put("code", 0);
        uploadData.put("msg", "上传成功");
        uploadData.put("data", "0");
        uploadData.put("id",id);
        JSONObject json = new JSONObject(uploadData);
        return json.toString();
     }
    

    /**
     * 
     * 简要说明:删除信息
     * 编写者:王云峰
     * 创建时间:2020-09-10
     * @param 说明
     * @return 说明
     */
    @PostMapping("remove")
    @ResponseBody
    public R remove() {
        String fileId=request.getParameter("fileId");//附件表id
        String daid=request.getParameter("daid");//关联表id
        //先获取附件路径,然后删除附件再删除数据
        THsapDaAttachment tHsapDaAttachment=tHsapDaAttachmentService.selectById(fileId);
        String filePath=UPLOAD_FILE_PATH+tHsapDaAttachment.getUploadname();
        FileUtil.del(filePath);//删除附件 建议用hutool Io工具类 很好使
        boolean result = tHsapDaAttachmentService.deleteById(fileId);
        if (result) {
            R r=R.ok();
            r.put("status", "success");
            return r;
        } else {
            R r=R.error();
            r.put("status", "error");
            return r;
        }

    }
    

修改页面

<div class="layui-col-md12">
        <div class="layui-card">
          <div class="layui-card-header"><strong>原文上传</strong>(只可上传五个原文,支持常用文件格式)
          </div>
          <div class="layui-card-body">
            <div class="layui-upload">
              <button type="button" class="layui-btn layui-btn-normal" id="test-upload-testList">选择多文件</button> 
              <div class="layui-upload-list">
                <table class="layui-table">
                  <thead>
                    <tr><th>文件名</th>
                    <th>状态</th>
                    <th>操作</th>
                  </tr></thead>
                  <tbody id="test-upload-demoList">
                     <tr  th:each="file,Stat:${fileList}"   th:id="'upload-'+(${Stat.index}+1)"> 
                        <td th:text="${file.attachname}"></td>  
                        <td><span style="color: #5FB878;">已上传</span></td>  
                        <td>
                            <button class="layui-btn layui-btn-xs layui-btn-danger demo-delete2" style="margin-left: 10px;" >删除</button>
                            <input class="layui-hide attId" th:value="${file.id}"  type="text">
                        </td>  
                      </tr>  
                  </tbody>
                </table>
              </div>
              <button type="button" class="layui-btn" style="background-color: #1E9FFF;" id="test-upload-testListAction">开始上传</button>
            </div> 
          </div>
        </div>
</div>

js部分

//多文件列表示例
            var demoListView = $('#test-upload-demoList')
              ,uploadListIns = upload.render({
              elem: '#test-upload-testList'
              ,url: cxt +'fileManage/tHsapDaAttachment/upload'
              ,accept: 'file'
              ,data: {token:token,source:'t_hsap_da_wenshu',daid:id,datype:1} //可选项。额外的参数,如:{id: 123, abc: 'xxx'}
              ,number:5
              ,multiple: true
              ,auto: false
              ,bindAction: '#test-upload-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>等待上传</td>'
                    ,'<td>'
                      ,'<button class="layui-btn layui-btn-xs test-upload-demo-reload layui-hide">重传</button>'
                      ,'<button class="layui-btn layui-btn-xs layui-btn-danger test-upload-demo-delete">删除</button>'
                    ,'</td>'
                  ,'</tr>'].join(''));
                  
                  //单个重传
                  tr.find('.test-upload-demo-reload').on('click', function(){
                    obj.upload(index, file);
                  });
                  
                  //删除
                  tr.find('.test-upload-demo-delete').on('click', function(){
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值,以免删除后出现同名文件不可选
                  });
                  
                  demoListView.append(tr);
                });
              }
              ,done: function(res, index, upload){
                if(res.code == 0){ //上传成功
                  var tr = demoListView.find('tr#upload-'+ index)
                  ,tds = tr.children();
                  tds.eq(1).html('<span style="color: #5FB878;">上传成功</span>');
                  tds.eq(2).html('<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete2" style="margin-left: 10px;">删除</button><input class="layui-hide attId" th:value="'+res.id+'"  type="text">'); //清空操作
                  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(1).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(2).find('.test-upload-demo-reload').removeClass('layui-hide'); //显示重传
              }
            });
            
            // 已有文件删除
            $('.demo-delete2').on('click', function(){
                var daid = $("#id").val();
                var fileId = $(this).parents("tr").find(".attId").val();
                var bt = $(this);
                //调用ajax删除附件表信息及附件
                $.ajax({
                      type: "post",
                    url : cxt +'fileManage/tHsapDaAttachment/remove',
                    async : false, //同步执行
                    data : {daid:daid,fileId:fileId,token:token},
                    dataType : "json",
                    success : function(data) {
                        if(data.status == "success"){    
                            bt.parent().parent().remove();
                            /* $(this).parents("tr").remove(); */
                        }else{
                            top.layer.msg('删除附件失败', {
                                  icon: 0,
                                  time: 2000 //2秒关闭(如果不配置,默认是3秒)
                            }, function(){
                                
                            });
                        }
                    },error: function() {
                        top.layer.msg('删除附件失败', {
                              icon: 0,
                              time: 2000 //2秒关闭(如果不配置,默认是3秒)
                        }, function(){
                            
                        });
                    }
                });
                
            });

 

相关文章: