整合百度 WebUploader 上傳插件,里面含上傳進(jìn)度條,md5 驗(yàn)證查看文件是否存在,達(dá)到文件秒傳
 
 
 
 <script>
layui.config({
base: '../layui_exts/'
,version: '1.0.0'
}).extend({
layUploader:'uploader_ext/layUploader'
}).use('layUploader',function () {
var layUploader = layui.layUploader;
var $=layui.$;
$("#testdlg").click(function () {
layUploader.render({
url:'/up',//上傳文件服務(wù)器地址,必填
md5:'/md5',//md5驗(yàn)證地址,不填無(wú)md5驗(yàn)證,可不填
size:200*1024*1024,//單個(gè)文件大小,有默認(rèn)值,可不填
fileType:'doc,docx'//允許上傳文件格式,有默認(rèn)值,可不填
});
});
});
</script>
layui.extend({
    //你的webuploader.js路徑
    webuploader: 'uploader_ext/uploader/webuploader'
}).define(['layer','laytpl','table','element','webuploader'],function(exports){
    var $ = layui.$
        ,webUploader= layui.webuploader
        ,element = layui.element
        ,layer=layui.layer
        ,table=layui.table
        ,rowData=[]//保存上傳文件屬性集合,添加table用
        ,fileSize=100*1024*1024//默認(rèn)上傳文件大小
        ,fileType='doc,docx,pdf,xls,xlsx,ppt,pptx,gif,jpg,jpeg,bmp,png,rar,zip'
        ,uplaod;
    //加載樣式
    layui.link('layui_exts/uploader_ext/uploader/webuploader.css');
    var Class = function (options) {
        var that = this;
        that.options=options;
        that.register();
        that.init();
        that.events();
    };
    Class.prototype.init=function(){
        var that = this,
            options=that.options;
        if(!that.strIsNull(options.size)){
            fileSize=options.size
        }
        if(!that.strIsNull(that.options.fileType)){
            fileType=that.options.fileType;
        }
        layer.open({
            type: 1,
            area: ['850px', '500px'], //寬高
            resize:false,
            content:
            '<div  id="extend-upload-chooseFile" style="float: left;margin-left: 5px;margin-top: 5px;">選擇文件</div>'+
            '<button id="extent-button-uploader" class="layui-btn" style="height: 37px;margin-top: 5px;margin-left: 5px;">開(kāi)始上傳</button>'+
            '<table style="margin-top:-10px;" class="layui-table" id="extend-uploader-form" lay-filter="extend-uploader-form">' +
                '  <thead>' +
            '    <tr>' +
            '      <th lay-data="{type:\'numbers\', fixed:\'left\'}"></th>' +
            '      <th lay-data="{field:\'fileName\', width:250}">文件名稱(chēng)</th>' +
            '      <th lay-data="{field:\'fileSize\', width:100}">文件大小</th>' +
            '      <th lay-data="{field:\'validateMd5\', width:120}">文件驗(yàn)證</th>' +
            '      <th lay-data="{field:\'progress\',width: 200,templet:\'#button-form-optProcess\'}">進(jìn)度</th>' +
            '      <th lay-data="{field:\'oper\', width: 100,templet: \'#button-form-uploadTalbe\'}">操作</th>' +
            '    </tr>' +
            '  </thead>'+
            '</table>'+
            '<script type="text/html" id="button-form-uploadTalbe">'+
                '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>'+
            '</script>'+
            '<script type="text/html" id="button-form-optProcess">' +
                '<div style="margin-top: 5px;" class="layui-progress layui-progress-big" lay-filter="{{d.fileId}}"  lay-showPercent="true">'+
                  '<div class="layui-progress-bar layui-bg-blue" lay-percent="0%"></div>'+
                '</div>'+
            '</script>'
            ,
            success: function(layero, index){
                table.init('extend-uploader-form',{
                    height: 380,
                    unresize:true
                });
                console.log(options.url);
                uplaod = webUploader.create({
                    // 不壓縮image
                    resize: false,
                    // swf文件路徑
                    swf:  'src/lib/extend/uploader/Uploader.swf',
                    // 默認(rèn)文件接收服務(wù)端。
                    server: options.url,
                    pick: '#extend-upload-chooseFile',
                    fileSingleSizeLimit:fileSize,//單個(gè)文件大小
                    //接收文件類(lèi)型--自行添加options
                    accept:[{
                        title: 'file',
                        extensions: fileType,
                        mimeTypes: that.buildFileType(fileType)
                    }]
                });
            }//可以自行添加按鈕關(guān)閉,關(guān)閉請(qǐng)清空rowData
            ,end:function () {
                rowData=[];
                if(options.success){
                    if(typeof options.success==='function') {
                        options.success();
                    }
                }
            }
        });
    };
    Class.prototype.formatFileSize=function(size){
        var fileSize =0;
        if(size/1024>1024){
            var len = size/1024/1024;
            fileSize = len.toFixed(2) +"MB";
        }else if(size/1024/1024>1024){
            var len = size/1024/1024;
            fileSize = len.toFixed(2)+"GB";
        }else{
            var len = size/1024;
            fileSize = len.toFixed(2)+"KB";
        }
        return fileSize;
    };
    Class.prototype.buildFileType=function (type) {
        var ts = type.split(',');
        var ty='';
        for(var i=0;i<ts.length;i++){
            ty=ty+ "."+ts[i]+",";
        }
        return  ty.substring(0, ty.length - 1)
    };
    Class.prototype.strIsNull=function (str) {
        if(typeof str == "undefined" || str == null || str == "")
            return true;
        else
            return false;
    };
Class.prototype.events=function () {
        var that = this;
        //當(dāng)文件添加進(jìn)去
        uplaod.on('fileQueued', function( file ){
            var fileSize = that.formatFileSize(file.size);
            var row={fileId:file.id,fileName:file.name,fileSize:fileSize,validateMd5:'0%',progress:file.id,state:'就緒'};
            rowData.push(row);
            that.reloadData(rowData);
            element.render('progress');
        });
        //監(jiān)聽(tīng)進(jìn)度條,更新進(jìn)度條信息
        uplaod.on( 'uploadProgress', function( file, percentage ) {
            element.progress(file.id, (percentage * 100).toFixed(0)+'%');
        });
        //錯(cuò)誤信息監(jiān)聽(tīng)
        uplaod.on('error', function(handler){
            if(handler=='F_EXCEED_SIZE'){
                layer.msg('上傳的單個(gè)太大!。<br>操作無(wú)法進(jìn)行,如有需求請(qǐng)聯(lián)系管理員', {icon: 5});
            }else if(handler=='Q_TYPE_DENIED'){
                layer.msg('不允許上傳此類(lèi)文件!。<br>操作無(wú)法進(jìn)行,如有需求請(qǐng)聯(lián)系管理員', {icon: 5});
            }
        });
        //移除上傳的文件
        table.on('tool(extend-uploader-form)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                that.removeArray(rowData,data.fileId);
                uplaod.removeFile(data.fileId,true);
                obj.del();
            }
        });
        //開(kāi)始上傳
        $("#extent-button-uploader").click(function () {
            that.uploadToServer();
        });
        //單個(gè)文件上傳成功
        uplaod.on( 'uploadSuccess', function( file ) {
            that.setTableBtn(file.id,'完成');
        });
        //所有文件上傳成功后
        uplaod.on('uploadFinished',function(){//成功后
            $("#extent-button-uploader").text("開(kāi)始上傳");
            $("#extent-button-uploader").removeClass('layui-btn-disabled');
        });
    };
    Class.prototype.reloadData=function(data){
        layui.table.reload('extend-uploader-form',{
            data : data
        });
    };
    Class.prototype.register=function () {
        var that = this,
            options = that.options;
        if(that.strIsNull(options.md5)) {
            return;
        }
        // 在文件開(kāi)始發(fā)送前做些異步操作。做md5驗(yàn)證
        // WebUploader會(huì)等待此異步操作完成后,開(kāi)始發(fā)送文件。
        webUploader.Uploader.register({
            "before-send-file":"beforeSendFile"
        },{
            beforeSendFile: function(file){
                var task = new $.Deferred();
                (new webUploader.Uploader()).md5File(file, 0, 10*1024*1024).progress(function(percentage){
                    var v = that.getTableHead('validateMd5');
                    var table = $("#extend-uploader-form").next().find('div[class="layui-table-body layui-table-main"]').find('table');
                    var pro = table.find('td[data-field="progress"]');
                    for(var i=0;i<pro.length;i++){
                        var d = $(pro[i]).attr('data-content');
                        if(d==file.id ){
                            var t = $(pro[i]).prev();
                            t.empty();
                            t.append('<div class="'+v+'">'+(percentage * 100).toFixed(0)+'%</div>');
                        }
                    }
                }).then(function(val){
                    $.ajax({
                        type: "POST"
                        , url: options.md5
                        , data: {
                            type: "md5Check",md5: val //后臺(tái)接收 String md5
                        }
                        , cache: false
                        , timeout: 3000
                        , dataType: "json"
                    }).then(function(data, textStatus, jqXHR){
                        if(data.data==0){   //若存在,這返回失敗給WebUploader,表明該文件不需要上傳
                            task.reject(); //
                            uplaod.skipFile(file);
                            that.setTableBtn(file.id,'秒傳');
                            element.progress(file.id,'100%');
                        }else{
                            task.resolve();
                        }
                    }, function(jqXHR, textStatus, errorThrown){    //任何形式的驗(yàn)證失敗,都觸發(fā)重新上傳
                        task.resolve();
                    });
                });
                return $.when(task);
            }
        });
    };
    /***
     * 注意更改了table列的位置,或自行新增了表格,請(qǐng)自行在這修改
     */
    Class.prototype.getTableHead=function (field) {
        //獲取table頭的單元格class,保證動(dòng)態(tài)設(shè)置table內(nèi)容后單元格不變形
        var div = $("#extend-uploader-form").next().find('div[class="layui-table-header"]');
        var div2 = div[0];
        var table = $(div2).find('table');
        var td = table.find('th[data-field="'+field+'"]').find('div').attr('class');
        return td;
    };
    Class.prototype.setTableBtn=function (fileId,val) {
        var td = this.getTableHead('oper');
        //獲取操作欄,修改其狀態(tài)
        var table = $("#extend-uploader-form").next().find('div[class="layui-table-body layui-table-main"]').find('table');
        var pro = table.find('td[data-field="progress"]');
        for(var i=0;i<pro.length;i++){
            var d = $(pro[i]).attr('data-content');
            if(d==fileId ){
                var t = $(pro[i]).next();
                t.empty();
                t.append('<div class="'+td+'"><a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="ok">'+val+'</a></div>')
            }
        }
    };
    Class.prototype.uploadToServer=function () {
        if(rowData.length<=0){
            layer.msg('沒(méi)有上傳的文件', {icon: 5});
            return;
        }
        $("#extent-button-uploader").text("正在上傳");
        $("#extent-button-uploader").addClass('layui-btn-disabled');
        uplaod.upload();
    };
    Class.prototype.removeArray=function (array,fileId) {
        for(var i=0;i<array.length;i++){
            if(array[i].fileId==fileId){
                array.splice(i,1);
            }
        }
        return array;
    };
    var layUploader = {
        render:function (options) {
            var inst = new Class(options);
            return inst;
        }
    };
    exports('layUploader', layUploader);
});
                        該擴(kuò)展組件由第三方用戶(hù)主動(dòng)投遞,并由其自身進(jìn)行維護(hù),本站僅做收集。