本篇文章上一篇:css
對百度WebUploader開源上傳控件的二次封裝,精簡前端代碼(兩句代碼搞定上傳)html
此篇是在上面的基礎上擴展出來專門上傳圖片的控件封裝.前端
首先咱們看看效果:web
使用方式一樣很簡單,首先建立HTML容器以下:json
<div id="uploader" class="uploaderPic"> </div>
而後頁面加載完成後渲染:瀏覽器
$(function () { $("#uploader").powerWebUpload({ auto: false }); })
就搞定了.app
下面仍是老規矩,直接上源碼:dom
/* 基於百度webuploader的圖片上傳JQ插件(需引用JQ) 做者:顧振印 時間:2016-07-07 */ (function ($, window) { var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../.."; var UpdataLoadarrayObj = new Array(); function SuiJiNum() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } function initWebUpload(item, options) { if (!WebUploader.Uploader.support()) { var error = "上傳控件不支持您的瀏覽器!請嘗試升級flash版本或者使用Chrome引擎的瀏覽器。<a target='_blank' href='http://se.360.cn'>下載頁面</a>"; if (window.console) { window.console.log(error); } $(item).text(error); return; } var target = $(item);//容器 if (target.find(".uploader-list").length > 0) { return; } //建立默認參數 var defaults = { auto: true, hiddenInputId: "uploadifyHiddenInputId", // input hidden id onAllComplete: function (event) { }, // 當全部file都上傳後執行的回調函數 onComplete: function (event) { },// 每上傳一個file的回調函數 fileNumLimit: undefined,//驗證文件總數量, 超出則不容許加入隊列 fileSizeLimit: undefined,//驗證文件總大小是否超出限制, 超出則不容許加入隊列。 fileSingleSizeLimit: undefined,//驗證單個文件大小是否超出限制, 超出則不容許加入隊列 PostbackHold: false }; var opts = $.extend(defaults, options); var hdFileData = $("#" + opts.hiddenInputId); var pickerid = ""; if (typeof guidGenerator36 != 'undefined')//給一個惟一ID pickerid = guidGenerator36(); else pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); var uploaderStrdiv = '<div class="webuploader">' if (opts.auto) { uploaderStrdiv = '<div class="uploader-list"></div>' + '<div class="btns">' + '<div id="' + pickerid + '">選擇文件</div>' + '</div>' } else { uploaderStrdiv = '<div class="uploader-list"></div>' + '<div class="btns">' + '<div id="' + pickerid + '">選擇文件</div>' + '<button class="webuploadbtn">開始上傳</button>' + '</div>' } uploaderStrdiv += '<div style="display:none" class="UploadhiddenInput" >\ </div>' uploaderStrdiv += '</div>'; target.append(uploaderStrdiv); var $list = target.find('.uploader-list'), $btn = target.find('.webuploadbtn'),//手動上傳按鈕備用 state = 'pending', $hiddenInput = target.find('.UploadhiddenInput') var jsonData = { fileList: [] }; debugger; var webuploaderoptions = $.extend({ // swf文件路徑 swf: applicationPath + '/Scripts/webuploader/Uploader.swf', // 文件接收服務端。 server: '/Home/AddFile', deleteServer: '/Home/DeleteFile', // 選擇文件的按鈕。可選。 // 內部根據當前運行是建立,多是input元素,也多是flash. pick: '#' + pickerid, //不壓縮image, 默認若是是jpeg,文件上傳前會壓縮一把再上傳! resize: false, runtimeOrder: 'flash', fileNumLimit: opts.fileNumLimit, fileSizeLimit: opts.fileSizeLimit, fileSingleSizeLimit: opts.fileSingleSizeLimit, //限制只能上傳圖片,格式gif,jpg,jpeg,bmp,png accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }, opts); var uploader = WebUploader.create(webuploaderoptions); UpdataLoadarrayObj[$(item)[0].id] = uploader; var ratio = window.devicePixelRatio || 1 // 縮略圖大小 var thumbnailWidth = 110 * ratio var thumbnailHeight = 110 * ratio if (opts.auto) { // 優化retina, 在retina下這個值是2 uploader.on('fileQueued', function (file) { var $li = $('<div id="' + $(item)[0].id + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>'); $img = $li.find('img'); uploader.makeThumb(file, function (error, src) { if (error) { $img.replaceWith('<span>不能預覽</span>'); return; } $img.attr('src', src); }, thumbnailWidth, thumbnailHeight); // $list爲容器jQuery實例 $list.append($li); $btns = $('<div class="file-panel">' + '<span class="cancel">刪除</span>').appendTo($li) uploader.upload(); }); } else { uploader.on('fileQueued', function (file) {//隊列事件 var $li = $('<div id="' + $(item)[0].id + file.id + '" class="file-item thumbnail">' + '<img>' + '<div class="info">' + file.name + '</div>' + '</div>'); $img = $li.find('img'); uploader.makeThumb(file, function (error, src) { if (error) { $img.replaceWith('<span>不能預覽</span>'); return; } $img.attr('src', src); }, thumbnailWidth, thumbnailHeight); // $list爲容器jQuery實例 $list.append($li); $btns = $('<div class="file-panel">' + '<span class="cancel">刪除</span>').appendTo($li) }); } // 文件上傳過程當中建立進度條實時顯示。 uploader.on('uploadProgress', function (file, percentage) { var $li = $('#' + $(item)[0].id + file.id), $percent = $li.find('.progress span'); // 避免重複建立 if (!$percent.length) { $percent = $('<p class="progress"><span></span></p>') .appendTo($li) .find('span'); } $percent.css('width', percentage * 100 + '%'); }); // 文件上傳成功,給item添加成功class, 用樣式標記上傳成功。 uploader.on('uploadSuccess', function (file, response) { $('#' + $(item)[0].id + file.id).addClass('upload-state-done'); var $li = $('#' + $(item)[0].id + file.id), $error = $li.find('div.error'); // 避免重複建立 if (!$error.length) { $error = $('<div class="success"></div>').appendTo($li); } if (response.state == "error") { $error.text(response.message); } else { $error.text('上傳完成'); $hiddenInput.append('<input type="text" id="hiddenInput' + $(item)[0].id + file.id + '" class="hiddenInput" value="' + response.message + '" />') } }); // 文件上傳失敗,顯示上傳出錯。 uploader.on('uploadError', function (file) { var $li = $('#' + $(item)[0].id + file.id), $error = $li.find('div.error'); // 避免重複建立 if (!$error.length) { $error = $('<div class="error"></div>').appendTo($li); } $error.text('上傳失敗'); }); // 完成上傳完了,成功或者失敗,先刪除進度條。 uploader.on('uploadComplete', function (file, response) { $('#' + $(item)[0].id + file.id).find('.progress').remove(); }); //uploader.on('uploadProgress', function (file, percentage) {//進度條事件 // var $li = target.find('#' + $(item)[0].id + file.id), // $percent = $li.find('.progress .bar'); // // 避免重複建立 // if (!$percent.length) { // $percent = $('<span class="progress">' + // '<span class="percentage"><span class="text"></span>' + // '<span class="bar" role="progressbar" style="width: 0%">' + // '</span></span>' + // '</span>').appendTo($li).find('.bar'); // } // $li.find('span.webuploadstate').html('上傳中'); // $li.find(".text").text(Math.round(percentage * 100) + '%'); // $percent.css('width', percentage * 100 + '%'); //}); //uploader.on('uploadSuccess', function (file, response) {//上傳成功事件 // if (response.state == "error") { // target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html(response.message); // } else { // target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('已上傳'); // $hiddenInput.append('<input type="text" id="hiddenInput' + $(item)[0].id + file.id + '" class="hiddenInput" value="' + response.message + '" />') // } //}); //uploader.on('uploadError', function (file) { // target.find('#' + $(item)[0].id + file.id).find('span.webuploadstate').html('上傳出錯'); //}); //uploader.on('uploadComplete', function (file) {//所有完成事件 // target.find('#' + $(item)[0].id + file.id).find('.progress').fadeOut(); //}); uploader.on('all', function (type) { if (type === 'startUpload') { state = 'uploading'; } else if (type === 'stopUpload') { state = 'paused'; } else if (type === 'uploadFinished') { state = 'done'; } if (state === 'uploading') { $btn.text('暫停上傳'); } else { $btn.text('開始上傳'); } }); //刪除時執行的方法 uploader.on('fileDequeued', function (file) { debugger; var fullName = $("#hiddenInput" + $(item)[0].id + file.id).val(); if (fullName != null) { $.post(webuploaderoptions.deleteServer, { fullName: fullName }, function (data) { // alert(data.message); }) } $("#" + $(item)[0].id + file.id).remove(); $("#hiddenInput" + $(item)[0].id + file.id).remove(); }) //多文件點擊上傳的方法 $btn.on('click', function () { if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); } }); //刪除 $list.on("click", ".file-panel", function () { debugger var $ele = $(this); var id = $ele.parent().attr("id"); var id = id.replace($(item)[0].id, ""); var file = uploader.getFile(id); uploader.removeFile(file); }); } $.fn.CleanUpload = function (options) { var uploadrFile = UpdataLoadarrayObj[$(this).attr("id")] var fileslist = uploadrFile.getFiles(); for (var i in fileslist) { uploadrFile.removeFile(fileslist[i]); } //var ele = $(this); //var filesdata = ele.find(".UploadhiddenInput"); //filesdata.find(".hiddenInput").remove(); //ele.find(".uploader-list .item").remove(); } $.fn.GetFilesAddress = function (options) { var ele = $(this); var filesdata = ele.find(".UploadhiddenInput"); var filesAddress = []; filesdata.find(".hiddenInput").each(function () { filesAddress.push($(this).val()); }) return filesAddress; } $.fn.powerWebUpload = function (options) { var ele = this; if (typeof WebUploader == 'undefined') { var casspath = applicationPath + "/Scripts/webuploader/webuploader.css"; $("<link>").attr({ rel: "stylesheet", type: "text/css", href: casspath }).appendTo("head"); var jspath = applicationPath + "/Scripts/webuploader/webuploader.min.js"; $.getScript(jspath).done(function () { initWebUpload(ele, options); }) .fail(function () { alert("請檢查webuploader的路徑是否正確!") }); } else { initWebUpload(ele, options); } } })(jQuery, window);
由於有一些樣式上的東西,因此還須要添加一部分CSS以下:jsp
#container { color: #838383; font-size: 12px; } .uploaderPic .queueList { margin: 20px; border: 3px dashed #e6e6e6; } .uploaderPic .queueList.filled { padding: 17px; margin: 0; border: 3px dashed transparent; } .uploaderPic .queueList.webuploader-dnd-over { border: 3px dashed #999999; } .uploaderPic p { margin: 0; } .element-invisible { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px,1px,1px,1px); } .uploaderPic .placeholder { min-height: 350px; padding-top: 178px; text-align: center; background: url(../images/image.png) center 93px no-repeat; color: #cccccc; font-size: 18px; position: relative; } .uploaderPic .placeholder .webuploader-pick { font-size: 18px; background: #00b7ee; border-radius: 3px; line-height: 44px; padding: 0 30px; *width: 120px; color: #fff; display: inline-block; margin: 0 auto 20px auto; cursor: pointer; box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1); } .uploaderPic .placeholder .webuploader-pick-hover { background: #00a2d4; } .uploaderPic .placeholder .flashTip { color: #666666; font-size: 12px; position: absolute; width: 100%; text-align: center; bottom: 20px; } .uploaderPic .placeholder .flashTip a { color: #0785d1; text-decoration: none; } .uploaderPic .placeholder .flashTip a:hover { text-decoration: underline; } .uploaderPic .filelist { list-style: none; margin: 0; padding: 0; } .uploaderPic .filelist:after { content: ''; display: block; width: 0; height: 0; overflow: hidden; clear: both; } .uploaderPic .filelist li { width: 110px; height: 110px; background: url(../images/bg.png) no-repeat; text-align: center; margin: 0 8px 20px 0; position: relative; display: inline; float: left; overflow: hidden; font-size: 12px; } .uploaderPic .filelist li p.log { position: relative; top: -45px; } .uploaderPic .filelist li p.title { position: absolute; top: 0; left: 0; width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; top: 5px; text-indent: 5px; text-align: left; } .uploaderPic .filelist li p.progress { position: absolute; width: 100%; bottom: 0; left: 0; height: 8px; overflow: hidden; z-index: 50; margin: 0; border-radius: 0; background: none; -webkit-box-shadow: 0 0 0; } .uploaderPic .filelist li p.progress span { display: none; overflow: hidden; width: 0; height: 100%; background: #1483d8 url(../images/progress.png) repeat-x; -webit-transition: width 200ms linear; -moz-transition: width 200ms linear; -o-transition: width 200ms linear; -ms-transition: width 200ms linear; transition: width 200ms linear; -webkit-animation: progressmove 2s linear infinite; -moz-animation: progressmove 2s linear infinite; -o-animation: progressmove 2s linear infinite; -ms-animation: progressmove 2s linear infinite; animation: progressmove 2s linear infinite; -webkit-transform: translateZ(0); } @@-webkit-keyframes progressmove { 0% { background-position: 0 0; } 100% { background-position: 17px 0; } } @@-moz-keyframes progressmove { 0% { background-position: 0 0; } 100% { background-position: 17px 0; } } @@keyframes progressmove { 0% { background-position: 0 0; } 100% { background-position: 17px 0; } } .uploaderPic .filelist li p.imgWrap { position: relative; z-index: 2; line-height: 110px; vertical-align: middle; overflow: hidden; width: 110px; height: 110px; -webkit-transform-origin: 50% 50%; -moz-transform-origin: 50% 50%; -o-transform-origin: 50% 50%; -ms-transform-origin: 50% 50%; transform-origin: 50% 50%; -webit-transition: 200ms ease-out; -moz-transition: 200ms ease-out; -o-transition: 200ms ease-out; -ms-transition: 200ms ease-out; transition: 200ms ease-out; } .uploaderPic .filelist li img { width: 100%; } .uploaderPic .filelist li p.error { background: #f43838; color: #fff; position: absolute; bottom: 0; left: 0; height: 28px; line-height: 28px; width: 100%; z-index: 100; } .uploaderPic .filelist li .success { display: block; position: absolute; left: 0; bottom: 0; height: 40px; width: 100%; z-index: 200; background: url(../images/success.png) no-repeat right bottom; } .uploaderPic .filelist div.file-panel { position: absolute; height: 0; filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#80000000', endColorstr='#80000000')\0; background: rgba( 0, 0, 0, 0.5 ); width: 100%; top: 0; left: 0; overflow: hidden; z-index: 300; } .uploaderPic .filelist div.file-panel span { width: 24px; height: 24px; display: inline; float: right; text-indent: -9999px; overflow: hidden; background: url(../images/icons.png) no-repeat; margin: 5px 1px 1px; cursor: pointer; } .uploaderPic .filelist div.file-panel span.rotateLeft { background-position: 0 -24px; } .uploaderPic .filelist div.file-panel span.rotateLeft:hover { background-position: 0 0; } .uploaderPic .filelist div.file-panel span.rotateRight { background-position: -24px -24px; } .uploaderPic .filelist div.file-panel span.rotateRight:hover { background-position: -24px 0; } .uploaderPic .filelist div.file-panel span.cancel { background-position: -48px -24px; } .uploaderPic .filelist div.file-panel span.cancel:hover { background-position: -48px 0; } .uploaderPic .statusBar { height: 63px; border-top: 1px solid #dadada; padding: 0 20px; line-height: 63px; vertical-align: middle; position: relative; } .uploaderPic .statusBar .progress { border: 1px solid #1483d8; width: 198px; background: #fff; height: 18px; position: relative; display: inline-block; text-align: center; line-height: 20px; color: #6dbfff; position: relative; margin: 0 10px 0 0; } .uploaderPic .statusBar .progress span.percentage { width: 0; height: 100%; left: 0; top: 0; background: #1483d8; position: absolute; } .uploaderPic .statusBar .progress span.text { position: relative; z-index: 10; } .uploaderPic .statusBar .info { display: inline-block; font-size: 14px; color: #666666; } .uploaderPic .statusBar .btns { position: absolute; top: 10px; right: 20px; line-height: 40px; } #filePicker2 { display: inline-block; float: left; } .uploaderPic .statusBar .btns .webuploader-pick, .uploaderPic .statusBar .btns .uploadBtn, .uploaderPic .statusBar .btns .uploadBtn.state-uploading, .uploaderPic .statusBar .btns .uploadBtn.state-paused { background: #ffffff; border: 1px solid #cfcfcf; color: #565656; padding: 0 18px; display: inline-block; border-radius: 3px; margin-left: 10px; cursor: pointer; font-size: 14px; float: left; } .uploaderPic .statusBar .btns .webuploader-pick-hover, .uploaderPic .statusBar .btns .uploadBtn:hover, .uploaderPic .statusBar .btns .uploadBtn.state-uploading:hover, .uploaderPic .statusBar .btns .uploadBtn.state-paused:hover { background: #f0f0f0; } .uploaderPic .statusBar .btns .uploadBtn { background: #00b7ee; color: #fff; border-color: transparent; } .uploaderPic .statusBar .btns .uploadBtn:hover { background: #00a2d4; } .uploaderPic .statusBar .btns .uploadBtn.disabled { pointer-events: none; opacity: 0.6; }