写一个简单的批量文件上传插件

分享一个自己写的简单的批量文件上传插件:

基于jQuery
关于兼容性:支持目前市场上绝大多数的浏览器,IE的话最好选择IE8以上。

该插件很简单,由三个文件组成:easyUpload.js,easyUpload.css,以及loading.gif

js代码:easyUpload.js

(function ($) {
    $.fn.easyUpload = function (options) {
        var _elem = this;
        var _fileList = [];
        var defaults = {
            maxSize: 52428800,
            accept: '.doc,.docx,.xls,.xlsx,.ppt,.pptx,pdf,txt',
            multiple: true,
            maxFiles: 10
        };

        var opts = $.extend(defaults, options);

        function loading(show) {
            if (show) {
                _elem.find('.loading').css('top', _elem.offset().top + (_elem.height()/2 - 20));
                _elem.find('.loading').css('left', _elem.offset().left + (_elem.width()/2 - 67));
                _elem.find('.loading').show();
            } else {
                _elem.find('.loading').hide();
            }
        }

        function getSize(size) {
            if (size > opts.maxSize) {
                return '-';
            }
            if (size < 1024) {
                return size + 'B';
            }
            if (size < 1048576) {
                return Math.floor(size*100/1024)/100 + 'KB';
            }
            if (size < 52428800) {
                return Math.floor(size*100/1024/1024)/100 + 'KB';
            }
        }

        (function () {
            _elem.addClass('file-upload');
            _elem.append('<label class="select-btn">选择文件<input type="file" class="file-selector"></label>');
            _elem.append('<table class="file-list"><thead><tr><th>文件名</th><th width="100">大小</th><th width="100">状态</th><th width="100">操作</th></tr></thead><tbody></tbody></table>');
            _elem.append('<label class="upload-btn">开始上传</label>');
            _elem.append('<label class="cancel-btn">取消上传</label>');
            _elem.append('<div class="loading"><img src="easyUpload/loading.gif"><span>文件上传中...</span></div>');

            if (opts.accept != undefined) {
                _elem.find('.file-selector').attr('accept', opts.accept);
            }

            if (opts.multiple == true) {
                _elem.find('.file-selector').attr('multiple', 'multiple');
            }

            // 选择文件
            _elem.on('change', '.file-selector', function () {
                var files = $(this)[0].files;
                if (files.length > 0) {
                    if (_fileList.length + files.length > opts.maxFiles) {
                        alert('文件数量超过最大限制(>'+ opts.maxFiles +'个)!');
                        return;
                    }
                    $(files).each(function () {
                        var tr = $('<tr></tr>');
                        tr.append('<td class="file-name" title="'+ this.name +'">'+ this.name +'</td>');
                        if (this.size > opts.maxSize) {
                            tr.append('<td class="file-size">-</td>');
                            tr.append('<td class="file-status" status="-1"><span class="oversize">文件过大</span></td>');
                        } else {
                            tr.append('<td class="file-size">'+ getSize(this.size) +'</td>');
                            tr.append('<td class="file-status" status="0">待上传</td>');
                        }
                        tr.append('<td><a href="javascript:void(0);" class="delete-btn">取消</a></td>');
                        _elem.find('.file-list').find('tbody').append(tr);
                        _fileList.push(this);
                    });
                }
            });

            // 取消上传
            _elem.on('click', '.cancel-btn', function () {
                $(_elem.find('.file-list').find('tbody').find('tr')).each(function () {
                    var currentTR = $(this);
                    if (currentTR.find('.file-status').attr('status') == 1) {
                        return;
                    }
                    _fileList.splice(currentTR.index(), 1);
                    currentTR.remove();
                });
            });

            // 取消
            _elem.on('click', '.delete-btn', function () {
                var currentTR = $(this).parent().parent();
                _fileList.splice(currentTR.index(), 1);
                currentTR.remove();
            });

            // 开始上传
            _elem.on('click', '.upload-btn', function () {
                if (_fileList.length == 0) {
                    return;
                }
                loading(true);
                $(_elem.find('.file-list').find('tbody').find('tr')).each(function () {
                    var currentTR = $(this);
                    if (currentTR.find('.file-size').text() == '-') {
                        return;
                    }
                    if (currentTR.find('.file-status').attr('status') == 0) {
                        if (opts.process(_fileList[currentTR.index()]) == true) {
                            currentTR.find('.file-status').attr('status', 1);
                            currentTR.find('.file-status').text('上传成功');
                            currentTR.find('.delete-btn').remove();
                        } else {
                            currentTR.find('.file-status'.attr('status', -1));
                            currentTR.find('.file-status').text('上传失败');
                        }
                    }
                });
                loading(false);
            });
        })();
    };
})(jQuery);
View Code

样式文件:easyUpload.css

.file-upload {
    display: inline-block;
    width: 500px;
}

.file-upload .file-selector {
    display: none;
}

.file-upload .select-btn,
.file-upload .upload-btn,
.file-upload .cancel-btn {
    display: inline-block;
    width: 70px;
    height: 25px;
    line-height: 25px;
    font-size: 14px;
    text-align: center;
    cursor: pointer;
    cursor: hand;
    background: #1c93f3;
    border: solid 1px #1c93f3;
    border-radius: 4px;
    color: #fff;
    margin-right: 20px;
}

.file-upload .file-list {
    border-collapse: collapse;
    border-spacing: 0;
    width: 100%;
    margin: 5px 0;
    font-size: 14px;
}

.file-upload .file-list tr {
    border: solid 1px #cbcbcb;
}

.file-upload .file-list tr:nth-child(even) {
    background: #f8f8f8;
}

.file-upload .file-list th {
    font-weight: normal;
    text-align: center;
    height: 20px;
    background: #e3e3e3;
}

.file-upload .file-list td {
    text-align: center;
    height: 20px;
    padding: 0 10px;
    font-size: 13px;
}

.file-upload .file-list td a {
    text-decoration: none;
    color: #2b669a;
}

.file-upload .delete-btn {
    /*margin: 0 5px;*/
}

.file-upload .loading {
    display: none;
    border: solid 2px #86A5AD;
    padding: 5px 10px;
    background: #fff;
    position: absolute;
}

.file-upload .loading span {
    vertical-align: top;
    line-height: 25px;
    margin-left: 5px;
    font-size: 15px;
    color: green;
}

.file-upload .oversize {
    color: red;
}

.file-upload .file-name {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    max-width: 220px;
}
View Code

以及loading图片:

参数说明:

maxSize: 单个文件允许上传的最大尺寸
multiple: 是否允许一次选取多个文件
maxFiles:设置当前组件能处理的最大文件数
accept:支持选取的文件格式(后缀)
process:文件处理函数,可以根据实际应用编写自己的逻辑

下面给出一个样例,使用起来也很简单:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta charset="UTF-8">
    <title>easyUpload - 批量文件上传</title>
    <link rel="stylesheet" href="easyUpload/easyUpload.css">
    <script type="application/javascript" src="jquery/jquery.min.js"></script>
    <script type="application/javascript" src="easyUpload/easyUpload.js"></script>
    <script type="application/javascript">
        $(function () {
            $('#fileUpload').easyUpload({
                maxSize: 10485760, // 单个文件最大尺寸10MB
                multiple: true, // 支持选择多个文件
                maxFiles: 5, // 插件最多处理5个文件
                accept: '.doc,.docx,.xls,.xlsx', // 仅上传word或excel文件
                process: function (file) {
                    var returnValue = true;
                    var formData = new FormData();
                    formData.append("file", file);
                    $.ajax({
                        url: '/upload',
                        type: 'post',
                        processData: false,
                        contentType: false,
                        data: formData,
                        success: function (result) {
                            // do some business logic...
                        },
                        error: function () {
                            returnValue = false;
                        }
                    })
                    return returnValue;
                }
            });
        });

    </script>
</head>
<body>
    <div id="fileUpload"></div>
</body>
</html>

效果如下:

猜你喜欢

转载自www.cnblogs.com/lichmama/p/10124582.html