Browse Source

重构文件上传表单JS代码

jqh 4 years ago
parent
commit
603c9f011c

+ 2 - 2
resources/assets/dcat/extra/Grid/Tree.js

@@ -22,11 +22,11 @@ export default class Tree {
         
         this.key = this.depth = this.row = this.data = this._req = null;
 
-        this._bind();
+        this._init();
     }
 
     // 绑定点击事件
-    _bind () {
+    _init () {
         var _this = this,
             opts = _this.options;
 

+ 284 - 0
resources/assets/dcat/extra/Upload/AddFile.js

@@ -0,0 +1,284 @@
+
+export default class AddFile {
+    constructor(Uploder) {
+        this.uploader = Uploder;
+    }
+
+    // 添加新文件
+    add(file) {
+        let _this = this,
+            parent = _this.uploader,
+            showImg = parent.isImage(),
+            size = WebUploader.formatSize(file.size),
+            $li,
+            $btns,
+            fileName = file.name || null;
+
+        if (showImg) {
+            $li = $(`<li id="${parent.getFileViewSelector(file.id)}" title="${fileName}" >
+                    <p class="file-type">${(file.ext.toUpperCase() || 'FILE')}</p>
+                    <p class="imgWrap "></p>
+                    <p class="title" style="">${file.name}</p>
+                    <p class="title" style="margin-bottom:20px;">(<b>${size}</b>)</p>
+                    </li>`);
+
+            $btns = $(`<div class="file-panel">
+                    <a class="btn btn-sm btn-white" data-file-act="cancel"><i class="feather icon-x red-dark" style="font-size:13px"></i></a>
+                    <a class="btn btn-sm btn-white" data-file-act="delete" style="display: none">
+                    <i class="feather icon-trash red-dark" style="font-size:13px"></i></a>
+                    <a class="btn btn-sm btn-white" data-file-act="preview" ><i class="feather icon-zoom-in"></i></a>
+                    <a class='btn btn-sm btn-white' data-file-act='order' data-order="1" style="display: none"><i class='feather icon-arrow-up'></i></a>
+                    <a class='btn btn-sm btn-white' data-file-act='order' data-order="0" style="display: none"><i class='feather icon-arrow-down'></i></a>
+
+                    </div>`).appendTo($li);
+        } else {
+            $li = $(`
+                    <li id="${parent.getFileViewSelector(file.id)}" title="${file.nam}">
+                    <p class="title" style="display:block">
+                        <i class="feather icon-check green _success icon-success"></i>
+                        ${file.name} (${size})
+                    </p>
+                    </li>
+                `);
+
+            $btns = $(`
+<span style="right: 45px;" class="file-action d-none" data-file-act='order' data-order="1"><i class='feather icon-arrow-up'></i></span>
+<span style="right: 25px;" class="file-action d-none" data-file-act='order' data-order="0"><i class='feather icon-arrow-down'></i></span>
+<span data-file-act="cancel" class="file-action" style="font-size:13px">
+    <i class="feather icon-x red-dark"></i>
+</span>
+<span data-file-act="delete" class="file-action" style="display:none">
+    <i class="feather icon-trash red-dark"></i>
+</span>
+`).appendTo($li);
+        }
+
+        $li.appendTo(parent.$files);
+
+        setTimeout(function () {
+            $li.css({margin: '5px'});
+        }, 50);
+
+        if (file.getStatus() === 'invalid') {
+            _this.showError($li, file.statusText, file);
+        } else {
+            if (showImg) {
+                // 显示图片
+                _this.showImage($li, file)
+            }
+
+            parent.percentages[file.id] = [file.size, 0];
+            file.rotation = 0;
+        }
+
+        file.on('statuschange', _this.resolveStatusChangeCallback($li, $btns, file));
+
+        let $act = showImg ? $btns.find('a') : $btns;
+
+        $act.on('click', _this.resolveActionsCallback(file));
+    }
+
+    // 显示错误信息
+    showError ($li, code, file) {
+        let _this = this,
+            __ = _this.uploader.lang.trans,
+            text = '',
+            $info = $('<p class="error"></p>');
+
+        switch (code) {
+            case 'exceed_size':
+                text = __('exceed_size');
+                break;
+
+            case 'interrupt':
+                text = __('interrupt');
+                break;
+
+            default:
+                text = __('upload_failed');
+                break;
+        }
+
+        _this.uploader.faildFiles[file.id] = file;
+
+        $info.text(text).appendTo($li);
+    }
+
+    // 显示图片
+    showImage($li, file) {
+        let _this = this,
+            uploader = _this.uploader.uploader,
+            $wrap = $li.find('p.imgWrap');
+
+        var image = uploader.makeThumb(file, function (error, src) {
+            var img;
+
+            $wrap.empty();
+            if (error) {
+                $li.find('.title').show();
+                $li.find('.file-type').show();
+                return;
+            }
+
+            if (_this.uploader.helper.isSupportBase64) {
+                img = $('<img src="' + src + '">');
+                $wrap.append(img);
+            } else {
+                $li.find('.file-type').show();
+            }
+        });
+
+        try {
+            image.once('load', function () {
+                file._info = file._info || image.info();
+                file._meta = file._meta || image.meta();
+                var width = file._info.width,
+                    height = file._info.height;
+
+                // 验证图片宽高
+                if (! _this.validateDimensions(file)) {
+                    Dcat.error('The image dimensions is invalid.');
+
+                    uploader.removeFile(file);
+
+                    return false;
+                }
+
+                image.resize(width, height);
+            });
+        } catch (e) {
+            // 不是图片
+            return setTimeout(function () {
+                uploader.removeFile(file);
+            }, 10);
+        }
+    }
+
+    // 状态变化回调
+    resolveStatusChangeCallback($li, $btns, file) {
+        let _this = this,
+            parent = _this.uploader;
+
+        return function (cur, prev) {
+            if (prev === 'progress') {
+                // $prgress.hide().width(0);
+            } else if (prev === 'queued') {
+                $btns.find('[data-file-act="cancel"]').hide();
+                $btns.find('[data-file-act="delete"]').show();
+            }
+
+            // 成功
+            if (cur === 'error' || cur === 'invalid') {
+                _this.showError($li, file.statusText, file);
+                parent.percentages[file.id][1] = 1;
+
+            } else if (cur === 'interrupt') {
+                _this.showError($li, 'interrupt', file);
+
+            } else if (cur === 'queued') {
+                parent.percentages[file.id][1] = 0;
+
+            } else if (cur === 'progress') {
+                // 移除错误信息
+                _this.removeError($li);
+                // $prgress.css('display', 'block');
+
+            } else if (cur === 'complete') {
+                if (_this.uploader.isImage()) {
+                    $li.append('<span class="success"><em></em><i class="feather icon-check"></i></span>');
+                } else {
+                    $li.find('._success').show();
+                }
+            }
+
+            $li.removeClass('state-' + prev).addClass('state-' + cur);
+        };
+    }
+
+    // 操作按钮回调
+    resolveActionsCallback(file) {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            helper = parent.helper;
+
+        return function () {
+            var index = $(this).data('file-act');
+
+            switch (index) {
+                case 'cancel':
+                    uploader.removeFile(file);
+                    return;
+                case 'deleteurl':
+                case 'delete':
+                    // 本地删除
+                    if (parent.options.removable) {
+                        parent.input.delete(file.serverId);
+
+                        return uploader.removeFile(file);
+                    }
+
+                    // 删除请求
+                    uploader.request.delete(file, function () {
+                        // 删除成功回调
+                        parent.input.delete(file.serverId);
+
+                        uploader.uploader.removeFile(file);
+                    });
+
+                    break;
+                case 'preview':
+                    Dcat.helpers.previewImage(parent.$wrapper.find('img').attr('src'), null, file.name);
+
+                    break;
+                case 'order':
+                    $(this).attr('data-id', file.serverId);
+
+                    helper.orderFiles($(this));
+
+                    break;
+            }
+
+        };
+    }
+
+    // 移除错误信息
+    removeError($li) {
+        $li.find('.error').remove()
+    }
+
+    // 图片宽高验证
+    validateDimensions(file) {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options,
+            dimensions = options.dimensions,
+            width = file._info.width,
+            height = file._info.height,
+            isset = Dcat.helpers.isset;
+
+        // The image dimensions is invalid.
+        if (! parent.isImage() || ! _this.isImage(file) || ! Dcat.helpers.len(options.dimensions)) {
+            return true;
+        }
+
+        if (
+            (isset(dimensions, 'width') && dimensions['width'] != width) ||
+            (isset(dimensions, 'min_width') && dimensions['min_width'] > width) ||
+            (isset(dimensions, 'max_width') && dimensions['max_width'] < width) ||
+            (isset(dimensions, 'height') && dimensions['height'] != height) ||
+            (isset(dimensions, 'min_height') && dimensions['min_height'] > height) ||
+            (isset(dimensions, 'max_height') && dimensions['max_height'] < height) ||
+            (isset(dimensions, 'ratio') && dimensions['ratio'] != (width / height))
+        ) {
+            return false;
+        }
+
+        return true;
+    }
+
+    // 判断是否是图片
+    isImage (file) {
+        return file.type.match(/^image/);
+    }
+}

+ 167 - 0
resources/assets/dcat/extra/Upload/AddUploadedFile.js

@@ -0,0 +1,167 @@
+
+export default class AddUploadedFile {
+    constructor(Uploder) {
+        this.uploader = Uploder;
+
+        // 已上传的文件
+        this.uploadedFiles = [];
+
+        this.init = false;
+    }
+
+    // 添加已上传文件
+    add(file) {
+        let _this = this,
+            parent =  _this.uploader,
+            options = parent.options,
+            showImg = parent.isImage(),
+            html = "";
+
+        html += "<li title='" + file.serverPath + "'>";
+
+        if (! showImg && options.sortable) {
+            // 文件排序
+            html += `
+<p style="right: 45px" class="file-action" data-file-act='order' data-order="1" data-id='${file.serverId}'><i class='feather icon-arrow-up'></i></p>
+<p style="right: 25px" class="file-action" data-file-act='order' data-order="0" data-id='${file.serverId}'><i class='feather icon-arrow-down'></i></p>
+`;
+        }
+
+        if (showImg) {
+            html += `<p class='imgWrap'><img src='${file.serverUrl}'></p>`
+        } else if (!options.disabled) {
+            html += `<p class="file-action" data-file-act="delete" data-id="${file.serverId}"><i class="feather icon-trash red-dark"></i></p>`;
+        }
+
+        html += "<p class='title' style=''><i class='feather icon-check text-white icon-success text-white'></i>";
+        html += file.serverPath;
+        html += "</p>";
+
+        if (showImg) {
+            html += "<p class='title' style='margin-bottom:20px;'>&nbsp;</p>";
+            html += "<div class='file-panel' >";
+
+            if (!options.disabled) {
+                html += `<a class='btn btn-sm btn-white' data-file-act='deleteurl' data-id='${file.serverId}'><i class='feather icon-trash red-dark' style='font-size:13px'></i></a>`;
+            }
+            html += `<a class='btn btn-sm btn-white' data-file-act='preview' data-url='${file.serverUrl}' ><i class='feather icon-zoom-in'></i></a>`;
+
+            if (options.sortable) {
+                // 文件排序
+                html += `
+<a class='btn btn-sm btn-white' data-file-act='order' data-order="1" data-id='${file.serverId}'><i class='feather icon-arrow-up'></i></a>
+<a class='btn btn-sm btn-white' data-file-act='order' data-order="0" data-id='${file.serverId}'><i class='feather icon-arrow-down'></i></a>
+`;
+            }
+
+            html += "</div>";
+        } else {
+
+        }
+
+        html += "</li>";
+        html = $(html);
+
+        if (!showImg) {
+            html.find('.file-type').show();
+            html.find('.title').show();
+            parent.$wrapper.css('background', 'transparent');
+        }
+
+        // 删除操作
+        let deleteFile = function () {
+            var fileId = $(this).data('id');
+
+            // 本地删除
+            if (options.removable) {
+                html.remove();
+
+                return _this.removeFormFile(fileId);
+            }
+
+            // 发起删除请求
+            parent.request.delete({serverId: fileId}, function () {
+                // 移除
+                html.remove();
+
+                _this.removeFormFile(fileId);
+            });
+        };
+
+        // 删除按钮点击事件
+        html.find('[data-file-act="deleteurl"]').click(deleteFile);
+        html.find('[data-file-act="delete"]').click(deleteFile);
+
+        // 文件排序
+        if (options.sortable) {
+            html.find('[data-file-act="order"').click(function () {
+                parent.helper.orderFiles($(this));
+            });
+        }
+
+        // 图片预览
+        html.find('[data-file-act="preview"]').click(function () {
+            var url = $(this).data('url');
+
+            Dcat.helpers.previewImage(url);
+        });
+
+        parent.formFiles[file.serverId] = file;
+
+        parent.input.add(file.serverId);
+
+        parent.$files.append(html);
+
+        if (showImg) {
+            setTimeout(function () {
+                html.css('margin', '5px');
+            }, _this.init ? 0 : 400);
+
+            _this.init = 1;
+        }
+    }
+
+    // 重新渲染已上传的文件
+    reRender() {
+        for (let i in this.uploadedFiles) {
+            if (this.uploadedFiles[i]) {
+                this.add(this.uploadedFiles[i])
+            }
+        }
+    }
+
+    // 移除已上传文件
+    removeFormFile(fileId) {
+        if (!fileId) {
+            return;
+        }
+
+        let _this = this,
+            parent = _this.uploader,
+            uploader = _this.uploader,
+            file = parent.formFiles[fileId];
+
+        parent.input.delete(fileId);
+
+        delete parent.formFiles[fileId];
+
+        if (uploader && !file.fake) {
+            uploader.removeFile(file);
+        }
+
+        parent.status.switch('decrOriginalFileNum');
+        parent.status.switch('incrFileNumLimit');
+
+        if (! Dcat.helpers.len(parent.formFiles) && ! Dcat.helpers.len(parent.percentages)) {
+            parent.status.switch('pending');
+        }
+    }
+
+    push(file) {
+        if (!file.serverId || this.uploader.helper.searchUploadedFile(file.serverId) !== -1) {
+            return;
+        }
+
+        this.uploadedFiles.push(file)
+    }
+}

+ 121 - 0
resources/assets/dcat/extra/Upload/Helper.js

@@ -0,0 +1,121 @@
+
+export default class Helper {
+    constructor(Uploder) {
+        this.uploader = Uploder;
+
+        this.isSupportBase64 = this.supportBase64();
+    }
+
+    // 判断是否支持base64
+    supportBase64() {
+        let data = new Image(),
+            support = true;
+
+        data.onload = data.onerror = function () {
+            if (this.width != 1 || this.height != 1) {
+                support = false;
+            }
+        };
+        data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
+
+        return support;
+    }
+
+    // 显示api响应的错误信息
+    showError(response) {
+        var message = 'Unknown error!';
+        if (response && response.data) {
+            message = response.data.message || message;
+        }
+
+        Dcat.error(message)
+    }
+
+    // 文件排序
+    orderFiles($this) {
+        var _this = this,
+            $li = $this.parents('li').first(),
+            fileId = $this.data('id'),
+            order = $this.data('order'),
+            $prev = $li.prev(),
+            $next = $li.next();
+
+        if (order) {
+            // 升序
+            if (!$prev.length) {
+                return;
+            }
+            _this.swrapUploadedFile(fileId, order);
+            _this.uploader.reRenderUploadedFiles();
+
+            return;
+        }
+
+        if (!$next.length) {
+            return;
+        }
+
+        _this.swrapUploadedFile(fileId, order);
+        _this.uploader.reRenderUploadedFiles();
+    }
+
+    // 交换文件排序
+    swrapUploadedFile(fileId, order) {
+        let _this = this,
+            parent = _this.uploader,
+            uploadedFiles = parent.addUploadedFile.uploadedFiles,
+            index = parseInt(_this.searchUploadedFile(fileId)),
+            currentFile = uploadedFiles[index],
+            prevFile = uploadedFiles[index - 1],
+            nextFile = uploadedFiles[index + 1];
+
+        if (order) {
+            if (index === 0) {
+                return;
+            }
+
+            uploadedFiles[index - 1] = currentFile;
+            uploadedFiles[index] = prevFile;
+        } else {
+            if (!nextFile) {
+                return;
+            }
+
+            uploadedFiles[index + 1] = currentFile;
+            uploadedFiles[index] = nextFile;
+        }
+
+        _this.setUploadedFilesToInput();
+    }
+
+    setUploadedFilesToInput() {
+        let _this = this,
+            parent = _this.uploader,
+            uploadedFiles = parent.addUploadedFile.uploadedFiles,
+            files = [],
+            i;
+
+        for (i in uploadedFiles) {
+            if (uploadedFiles[i]) {
+                files.push(uploadedFiles[i].serverId);
+            }
+        }
+
+        parent.input.set(files);
+    }
+
+    // 查找文件位置
+    searchUploadedFile(fileId) {
+        let _this = this,
+            parent = _this.uploader,
+            uploadedFiles = parent.addUploadedFile.uploadedFiles;
+
+        for (var i in uploadedFiles) {
+            if (uploadedFiles[i].serverId === fileId) {
+                return i;
+            }
+        }
+
+        return -1;
+    }
+}

+ 64 - 0
resources/assets/dcat/extra/Upload/Input.js

@@ -0,0 +1,64 @@
+
+export default class Input {
+    constructor(Uploder) {
+        this.uploader = Uploder;
+
+        this.$selector = Uploder.$selector.find(Uploder.options.inputSelector)
+    }
+
+    // 获取上传的文件名
+    get() {
+        let val = this.$selector.val();
+
+        return val ? val.split(',') : [];
+    }
+
+    // 增加文件名
+    add(id) {
+        let val = this.get();
+
+        val.push(id);
+
+        this.set(val);
+    }
+
+    // 设置表单值
+    set(arr) {
+        arr = arr.filter(function (v, k, self) {
+            return self.indexOf(v) === k;
+        }).filter(function (v) {
+            return v ? true : false;
+        });
+
+        // 手动触发change事件,方便监听文件变化
+        this.$selector.val(arr.join(',')).trigger('change');
+    }
+
+    // 删除表单值
+    delete(id) {
+        let _this = this;
+
+        _this.deleteUploadedFile(id);
+
+        if (!id) {
+            return _this.$selector.val('');
+        }
+
+        _this.set(_this.get().filter(function (v) {
+            return v != id;
+        }));
+    }
+
+    deleteUploadedFile(fileId) {
+        let addUploadedFile = this.uploader.addUploadedFile;
+
+        addUploadedFile.uploadedFiles = addUploadedFile.uploadedFiles.filter(function (v) {
+            return v.serverId != fileId;
+        });
+    }
+
+    // 移除字段验证错误提示信息
+    removeValidatorErrors() {
+        this.$selector.parents('.form-group,.form-label-group,.form-field').find('.with-errors').html('')
+    }
+}

+ 86 - 0
resources/assets/dcat/extra/Upload/Request.js

@@ -0,0 +1,86 @@
+
+export default class Request {
+    constructor(Uploader) {
+        this.uploader = Uploader;
+    }
+
+    delete(file, callback) {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options,
+            uploader = parent.uploader;
+
+        Dcat.confirm(parent.lang.trans('confirm_delete_file'), file.serverId, function () {
+            var post = options.deleteData;
+
+            post.key = file.serverId;
+
+            if (! post.key) {
+                parent.input.delete(file.serverId);
+
+                return uploader.removeFile(file);
+            }
+
+            post._column = parent.getColumn();
+            post._relation = parent.relation;
+
+            Dcat.loading();
+
+            $.post({
+                url: options.deleteUrl,
+                data: post,
+                success: function (result) {
+                    Dcat.loading(false);
+
+                    if (result.status) {
+                        callback(result);
+
+                        return;
+                    }
+
+                    parent.helper.showError(result)
+                }
+            });
+
+        });
+    }
+
+    // 保存已上传的文件名到服务器
+    update() {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            options = parent.options,
+            updateColumn = parent.getColumn(),
+            relation = _this.relation,
+            values = parent.input.get(), // 获取表单值
+            num = uploader.getStats().successNum,
+            form = $.extend({}, options.formData);
+
+        if (!num || !values || !options.autoUpdateColumn) {
+            return;
+        }
+
+        if (relation) {
+            if (!relation[1]) {
+                // 新增子表记录,则不调用update接口
+                return;
+            }
+
+            form[relation[0]] = {};
+
+            form[relation[0]][relation[1]] = {};
+            form[relation[0]][relation[1]][updateColumn] = values.join(',');
+        } else {
+            form[updateColumn] = values.join(',');
+        }
+
+        delete form['_relation'];
+        delete form['upload_column'];
+
+        $.post({
+            url: options.updateServer,
+            data: form,
+        });
+    }
+}

+ 345 - 0
resources/assets/dcat/extra/Upload/Status.js

@@ -0,0 +1,345 @@
+
+export default class Status {
+    constructor(Uploder) {
+        this.uploader = Uploder;
+
+        // 可能有pending, ready, uploading, confirm, done.
+        this.state = 'pending';
+
+        // 已上传文件数量
+        this.originalFilesNum = Dcat.helpers.len(Uploder.options.preview);
+    }
+
+    switch(val, args) {
+        let _this = this,
+            parent = _this.uploader;
+
+        args = args || {};
+
+        if (val === _this.state) {
+            return;
+        }
+
+        // 上传按钮状态
+        if (parent.$uploadButton) {
+            parent.$uploadButton.removeClass('state-' + _this.state);
+            parent.$uploadButton.addClass('state-' + val);
+        }
+
+        _this.state = val;
+
+        switch (_this.state) {
+            case 'pending':
+                _this.pending();
+
+                break;
+
+            case 'ready':
+                _this.ready();
+
+                break;
+
+            case 'uploading':
+                _this.uploading();
+
+                break;
+
+            case 'paused':
+                _this.paused();
+
+                break;
+
+            case 'confirm':
+                _this.confirm();
+
+                break;
+            case 'finish':
+                _this.finish();
+
+                break;
+            case 'decrOriginalFileNum':
+                _this.decrOriginalFileNum();
+
+                break;
+
+            case 'incrOriginalFileNum':
+                _this.incrOriginalFileNum();
+
+                break;
+
+            case 'decrFileNumLimit': // 减少上传文件数量限制
+                _this.decrFileNumLimit(args.num);
+
+                break;
+            case 'incrFileNumLimit': // 增加上传文件数量限制
+                _this.incrFileNumLimit(args.num || 1);
+
+                break;
+            case 'init': // 初始化
+                _this.init();
+
+                break;
+        }
+
+        // 更新状态显示
+        _this.updateStatusText();
+    }
+
+    incrOriginalFileNum() {
+        this.originalFilesNum++;
+    }
+
+    decrOriginalFileNum() {
+        if (this.originalFilesNum > 0) {
+            this.originalFilesNum--;
+        }
+    }
+
+    confirm() {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            stats;
+
+        if (uploader) {
+            parent.$progress.hide();
+            parent.$selector.find(parent.options.addFileButton).removeClass('element-invisible');
+            parent.$uploadButton.text(parent.lang.trans('start_upload'));
+
+            stats = uploader.getStats();
+
+            if (stats.successNum && !stats.uploadFailNum) {
+                _this.switch('finish');
+            }
+        }
+    }
+
+    paused() {
+        let _this = this,
+            parent = _this.uploader;
+
+        parent.$progress.show();
+        parent.$uploadButton.text(parent.lang.trans('go_on_upload'));
+    }
+
+    uploading() {
+        let _this = this,
+            parent = _this.uploader;
+
+        parent.$selector.find(parent.options.addFileButton).addClass('element-invisible');
+        parent.$progress.show();
+        parent.$uploadButton.text(parent.lang.trans('pause_upload'));
+    }
+
+    pending() {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options;
+
+        if (options.disabled) {
+            return;
+        }
+        parent.$placeholder.removeClass('element-invisible');
+        parent.$files.hide();
+        parent.$statusBar.addClass('element-invisible');
+
+        if (parent.isImage()) {
+            parent.$wrapper.removeAttr('style');
+            parent.$wrapper.find('.queueList').removeAttr('style');
+        }
+
+        parent.uploader.refresh();
+    }
+
+    // 减少上传文件数量限制
+    decrFileNumLimit(num) {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            fileLimit;
+
+        if (!uploader) {
+            return;
+        }
+        fileLimit = uploader.option('fileNumLimit');
+        num = num || 1;
+
+        if (fileLimit == '-1') {
+            fileLimit = 0;
+        }
+
+        num = fileLimit >= num ? fileLimit - num : 0;
+
+        if (num == 0) {
+            num = '-1';
+        }
+
+        uploader.option('fileNumLimit', num);
+    }
+
+    // 增加上传文件数量限制
+    incrFileNumLimit(num) {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            fileLimit;
+
+        if (!uploader) {
+            return;
+        }
+        fileLimit = uploader.option('fileNumLimit');
+        num = num || 1;
+
+        if (fileLimit == '-1') {
+            fileLimit = 0;
+        }
+
+        num = fileLimit + num;
+
+        uploader.option('fileNumLimit', num);
+    }
+
+    ready() {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options;
+
+        parent.$placeholder.addClass('element-invisible');
+        parent.$selector.find(parent.options.addFileButton).removeClass('element-invisible');
+        parent.$files.show();
+        if (!options.disabled) {
+            parent.$statusBar.removeClass('element-invisible');
+        }
+
+        parent.uploader.refresh();
+
+        if (parent.isImage()) {
+            parent.$wrapper.find('.queueList').css({'border': '1px solid #d3dde5', 'padding': '5px'});
+            // $wrap.find('.queueList').removeAttr('style');
+        }
+
+        // 移除字段验证错误信息
+        setTimeout(function () {
+            parent.input.removeValidatorErrors();
+        }, 10);
+    }
+
+    finish() {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options,
+            uploader = parent.uploader,
+            stats;
+
+        if (uploader) {
+            stats = uploader.getStats();
+            if (stats.successNum) {
+                Dcat.success(parent.lang.trans('upload_success_message', {success: stats.successNum}));
+
+                setTimeout(function () {
+                    if (options.upload.fileNumLimit == 1) {
+                        // 单文件上传,需要重置文件上传个数
+                        uploader.request('get-stats').numOfSuccess = 0;
+                    }
+                }, 10);
+
+            } else {
+                // 没有成功的图片,重设
+                _this.state = 'done';
+
+                Dcat.reload();
+            }
+        }
+    }
+
+    // 初始化
+    init() {
+        let _this = this,
+            parent = _this.uploader,
+            options = parent.options;
+
+        parent.$uploadButton.addClass('state-' + _this.state);
+        _this.updateProgress();
+
+        if (_this.originalFilesNum || options.disabled) {
+            parent.$placeholder.addClass('element-invisible');
+            if (!options.disabled) {
+                parent.$statusBar.show();
+            } else {
+                parent.$wrapper.addClass('disabled');
+            }
+            _this.switch('ready');
+        } else if (parent.isImage()) {
+            parent.$wrapper.removeAttr('style');
+            parent.$wrapper.find('.queueList').css('margin', '0');
+        }
+
+        parent.uploader.refresh();
+    }
+
+    // 状态文本
+    updateStatusText() {
+        let _this = this,
+            parent = _this.uploader,
+            uploader = parent.uploader,
+            __ = parent.lang.trans.bind(parent.lang),
+            text = '',
+            stats;
+
+        if (!uploader) {
+            return;
+        }
+
+        if (_this.state === 'ready') {
+            stats = uploader.getStats();
+            if (parent.fileCount) {
+                text = __('selected_files', {num: parent.fileCount, size: WebUploader.formatSize(parent.fileSize)});
+            } else {
+                showSuccess();
+            }
+        } else if (_this.state === 'confirm') {
+            stats = uploader.getStats();
+            if (stats.uploadFailNum) {
+                text = __('selected_has_failed', {success: stats.successNum, fail: stats.uploadFailNum});
+            }
+        } else {
+            showSuccess();
+        }
+
+        function showSuccess() {
+            stats = uploader.getStats();
+            if (stats.successNum) {
+                text = __('selected_success', {num: parent.fileCount, size: WebUploader.formatSize(parent.fileSize), success: stats.successNum});
+            }
+
+            if (stats.uploadFailNum) {
+                text += (text ? __('dot') : '') + __('failed_num', {fail: stats.uploadFailNum});
+            }
+        }
+
+        parent.$infoBox.html(text);
+    }
+
+    // 进度条更新
+    updateProgress() {
+        let _this = this,
+            parent = _this.uploader,
+            loaded = 0,
+            total = 0,
+            $bar = parent.$progress.find('.progress-bar'),
+            percent;
+
+        $.each(parent.percentages, function (k, v) {
+            total += v[0];
+            loaded += v[0] * v[1];
+        });
+
+        percent = total ? loaded / total : 0;
+        percent = Math.round(percent * 100) + '%';
+
+        $bar.text(percent);
+        $bar.css('width', percent);
+
+        _this.updateStatusText();
+    }
+}

File diff suppressed because it is too large
+ 154 - 973
resources/assets/dcat/extra/upload.js


+ 2 - 2
src/Form/Field/WebUploader.php

@@ -121,7 +121,7 @@ trait WebUploader
      */
     public function removable(bool $value = true)
     {
-        $this->options['disableRemove'] = ! $value;
+        $this->options['removable'] = ! $value;
 
         return $this;
     }
@@ -209,7 +209,7 @@ trait WebUploader
             'name'                => WebUploaderHelper::FILE_NAME,
             'fileVal'             => WebUploaderHelper::FILE_NAME,
             'isImage'             => false,
-            'disableRemove'       => false,
+            'removable'           => false,
             'chunked'             => false,
             'fileNumLimit'        => 10,
             // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。

Some files were not shown because too many files changed in this diff