layui的upload元件使用以及上傳阻止測試

忘塵天外天發表於2018-09-05

背景:頁面上一個按鈕,點選彈出上傳框,從按鈕的方法程式碼開始寫:處理未選擇檔案阻止上傳;通過判斷選擇檔案的數量,顯示或隱藏上傳按鈕;

在js中定義: function  uploadFile(){

    layer.open({

        type:1,

        title:'上傳檔案‘,

        area:['25%','400px'],

        content:'<div class="layui-form-item" style="margin-top:40px;">\

          <div class="layui-input-block">\

            <input class="layui-btn" type="button" id="chooseFIle" value="選擇檔案">\

            <span></span>\

          </div>\

        </div>\

          <div class="layui-form-item" style="margin-top:40px;">\

          <div class="layui-input-block">\

            <input class="layui-btn" type="button" id="uploadbtn" value="上傳">\

            <span></span>\

          </div>\

        </div>‘,

    btn:['關閉'],

    btn1:function(idx,ele){

        layer.closeAll();

      }

  })

createUpload();

}

 

var  files ;

function createUpload(){

      $("#uploadbtn").hide();

      $("#chooseFile").next().next("span").text("");

      layui.use(['upload'],function(){

        var uploadInst = upload.render({

            elem:'#chooseFile',

             url:' ',

              accept:'file',

             auto:false,

            multiple:true,

          acceptMime:'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',

          exts:'xls|xlsx',

          size:1024000,

          number:5,

          bindAction:'#uploadbtn',

          choose:function(obj){

            files = this.files = boj.pushFile();

            if(Object.keys(files).length>0){ $("#uploadbtn").show(); }

            obj.preview(function(index,file,result){

              $("#chooseFile").siblings("span").append("<div title='"+index+"'>"+file.name+"&nbsp;&nbsp;<span onclick='deletefile(\""+index+"\")'>&times;</span></div>")

               if(index>0) {$("#uploadbtn").show() ;}

              })

          },

        allDone:function(obj){  

            if(obj.successful){

              layer.msg(obj.total+"個檔案上傳成功!");

            }

          },

        error:function(){

          layer.alert("上傳成功!");

        }

    })

  }

}

function  deletefile(index){

  delete  files[index];

  $("#chooseFile").siblings("span").find("div[title="+index+"]").remove();

  if(!Object.keys(files).length>0){

      $("#uploadbtn").hide();

  }

 

}

 

相關文章