1. 程式人生 > >寫一個簡單的批量檔案上傳外掛

寫一個簡單的批量檔案上傳外掛

分享一個自己寫的簡單的批量檔案上傳外掛:

基於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>

 

效果如下: