百度多文件異步上傳控件webuploader基本用法解析
雙核瀏覽器下在chrome內(nèi)核中使用uploadify總有302問(wèn)題,也不知道如何修復(fù),之所以喜歡360瀏覽器是因?yàn)閹涂蛻艨刂其秩緝?nèi)核:
若頁(yè)面需默認(rèn)用極速核,增加標(biāo)簽:<meta name="renderer" content="webkit"/>
若頁(yè)面需默認(rèn)用ie兼容內(nèi)核,增加標(biāo)簽:<meta name="renderer" content="ie-comp"/>
若頁(yè)面需默認(rèn)用ie標(biāo)準(zhǔn)內(nèi)核,增加標(biāo)簽:<meta name="renderer" content="ie-stand"/>
要解決302問(wèn)題也很簡(jiǎn)單,就是html5的文件上傳,正好最近在ueditor里看到百度的webuploader,會(huì)自動(dòng)選擇flash html5,就是一個(gè)成熟的解決方案了。
先看前端,我們將最常用的操作封裝為插件,asp.net中和MVC中最好使用相對(duì)于應(yīng)用程序的絕對(duì)路徑,自行定義全局applicationPath :var applicationPath = "@(Href("~")=="/"?"":Href("~"))";
前端插件代碼:
(function ($, window) { var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../.."; function S4() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } function initWebUpload(item, options) { if (!WebUploader.Uploader.support()) { var error = "上傳控件不支持您的瀏覽器!請(qǐng)嘗試升級(jí)flash版本或者使用Chrome引擎的瀏覽器。<a target='_blank' href='http://se.#'>下載頁(yè)面</a>"; if (window.console) { window.console.log(error); } $(item).text(error); return; } var defaults = { hiddenInputId: "uploadifyHiddenInputId", // input hidden id onAllComplete: function (event) { }, // 當(dāng)所有file都上傳后執(zhí)行的回調(diào)函數(shù) onComplete: function (event) { },// 每上傳一個(gè)file的回調(diào)函數(shù) innerOptions: {}, fileNumLimit: undefined, fileSizeLimit: undefined, fileSingleSizeLimit: undefined, PostbackHold: false }; var opts = $.extend({}, defaults, options); var hdFileData = $("#" + opts.hiddenInputId); var target = $(item);//容器 var pickerid = ""; if (typeof guidGenerator36 != 'undefined')//給一個(gè)唯一ID pickerid = guidGenerator36(); else pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); var uploaderStrdiv = '<div class="webuploader">' + '<div id="thelist" class="uploader-list"></div>' + '<div class="btns">' + '<div id="' + pickerid + '">選擇文件</div>' + //'<a id="ctlBtn" class="btn btn-default">開(kāi)始上傳</a>' + '</div>' + '</div>'; target.append(uploaderStrdiv); var $list = target.find('#thelist'), $btn = target.find('#ctlBtn'),//這個(gè)留著,以便隨時(shí)切換是否要手動(dòng)上傳 state = 'pending', uploader; var jsonData = { fileList: [] }; var webuploaderoptions = $.extend({ // swf文件路徑 swf: applicationPath + '/Scripts/lib/webuploader/Uploader.swf', // 文件接收服務(wù)端。 server: applicationPath + '/MvcPages/WebUploader/Process', // 選擇文件的按鈕??蛇x。 // 內(nèi)部根據(jù)當(dāng)前運(yùn)行是創(chuàng)建,可能是input元素,也可能是flash. pick: '#' + pickerid, // 不壓縮image, 默認(rèn)如果是jpeg,文件上傳前會(huì)壓縮一把再上傳! resize: false, fileNumLimit: opts.fileNumLimit, fileSizeLimit: opts.fileSizeLimit, fileSingleSizeLimit: opts.fileSingleSizeLimit }, opts.innerOptions); var uploader = WebUploader.create(webuploaderoptions); //回發(fā)時(shí)還原h(huán)iddenfiled的保持?jǐn)?shù)據(jù) var fileDataStr = hdFileData.val(); if (fileDataStr && opts.PostbackHold) { jsonData = JSON.parse(fileDataStr); $.each(jsonData.fileList, function (index, fileData) { var newid = S4(); fileData.queueId = newid; $list.append('<div id="' + newid + '" class="item">' + '<div class="info">' + fileData.name + '</div>' + '<div class="state">已上傳</div>' + '<div class="del"></div>' + '</div>'); }); hdFileData.val(JSON.stringify(jsonData)); } uploader.on('fileQueued', function (file) {//隊(duì)列事件 $list.append('<div id="' + file.id + '" class="item">' + '<div class="info">' + file.name + '</div>' + '<div class="state">等待上傳...</div>' + '<div class="del"></div>' + '</div>'); }); uploader.on('uploadProgress', function (file, percentage) {//進(jìn)度條事件 var $li = target.find('#' + file.id), $percent = $li.find('.progress .bar'); // 避免重復(fù)創(chuàng)建 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('div.state').text('上傳中'); $li.find(".text").text(Math.round(percentage * 100) + '%'); $percent.css('width', percentage * 100 + '%'); }); uploader.on('uploadSuccess', function (file, response) {//上傳成功事件 target.find('#' + file.id).find('div.state').text('已上傳'); var fileEvent = { queueId: file.id, name: file.name, size: file.size, type: file.type, filePath: response.filePath }; jsonData.fileList.push(fileEvent) opts.onComplete(fileEvent); }); uploader.on('uploadError', function (file) { target.find('#' + file.id).find('div.state').text('上傳出錯(cuò)'); }); uploader.on('uploadComplete', function (file) {//全部完成事件 target.find('#' + file.id).find('.progress').fadeOut(); var fp = $("#" + opts.hiddenInputId); fp.val(JSON.stringify(jsonData)); opts.onAllComplete(jsonData.fileList); }); uploader.on('fileQueued', function (file) { uploader.upload(); }); uploader.on('filesQueued', function (file) { uploader.upload(); }); 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('開(kāi)始上傳'); } }); $btn.on('click', function () { if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); } }); //刪除 $list.on("click", ".del", function () { var $ele = $(this); var id = $ele.parent().attr("id"); var deletefile = {}; $.each(jsonData.fileList, function (index, item) { if (item && item.queueId === id) { uploader.removeFile(uploader.getFile(id));//不要遺漏 deletefile = jsonData.fileList.splice(index, 1)[0]; $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData)); $.post(applicationi + "/Webploader/Delete", { 'filepathname': deletefile.filePath }, function (returndata) { $ele.parent().remove(); }); return; } }); }); } $.fn.powerWebUpload = function (options) { var ele = this; if (typeof PowerJs != 'undefined') { $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.css", function () { }, 'css'); $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.min.js", function () { initWebUpload(ele, options); }); } else { initWebUpload(ele, options); } } })(jQuery, window);
頁(yè)面引入上述js后使用:
$("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" });
html端需要一個(gè)容器和hidden
<div id="uploader"></div> <asp:HiddenField ID="hfFilePath" ClientIDMode="Static" runat="server" />
MVC版后端文件接收,即便你是asp.net 引入mvc做ajax也是可以的:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; public class WebUploaderController : BaseController { public ActionResult Process(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file) { string filePathName = string.Empty;string localPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload\\Document"); if (Request.Files.Count == 0) { return Json(new { jsonrpc = 2.0, error = new { code = 102, message = "保存失敗" }, id = "id" }); } try { filePathName = //自己在這里處理文件保存并返回需要保存到hidden的數(shù)據(jù),文件在file或者Request.Files[0] } catch (Exception) { return Json(new { jsonrpc = 2.0, error = new { code = 103, message = "保存失敗" }, id = "id" }); } return Json(new { jsonrpc = "2.0", id = "id", filePath = urlPath + "/" + filePathName }); } static string urlPath = "../../Upload/Document"; public ActionResult Delete(string filePathName) { if (string.IsNullOrEmpty(filePathName)) { return Content("no"); } //為了安全 檢查一下路徑 不夠嚴(yán)謹(jǐn) 自行更具業(yè)務(wù)做更加細(xì)致的判斷 if (!filePathName.StartsWith(urlPath) || filePathName.Substring(6, filePathName.Length - 7).Contains("../")) { return Content("no!"); } string localFilePathName = this.Server.MapPath(filePathName); try { bool b = UploadifyManager.DeleteAttachment(localFilePathName); if (!b) throw new Exception("刪除文件失敗"); return Content("ok"); } catch { return Content("no"); } } }
一開(kāi)始發(fā)首頁(yè)被退下來(lái)了,現(xiàn)在重新編輯使內(nèi)容更加完整,優(yōu)化了插件代碼
完整demo: https://github.com/gxrsprite/AspnetMvcWebuploaderDemo
補(bǔ)充:
擴(kuò)展自定義參數(shù),利用uploadBeforeSend事件可以擴(kuò)展參數(shù),插件內(nèi)可根據(jù)需要修改。
cookie的問(wèn)題,我用微軟自帶的登錄系統(tǒng),不需要做任何特殊處理完全沒(méi)有問(wèn)題。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 關(guān)于webuploader插件使用過(guò)程遇到的小問(wèn)題
- 推薦三款不錯(cuò)的圖片壓縮上傳插件(webuploader、localResizeIMG4、LUploader)
- 使用WebUploader實(shí)現(xiàn)上傳文件功能(一)
- 快速掌握jQuery插件WebUploader文件上傳
- webuploader 實(shí)現(xiàn)圖片批量上傳功能附實(shí)例代碼
- webuploader實(shí)現(xiàn)上傳圖片到服務(wù)器功能
- webuploader模態(tài)框ueditor顯示問(wèn)題解決方法
- 使用WebUploader實(shí)現(xiàn)分片斷點(diǎn)上傳文件功能(二)
- webuploader分片上傳的實(shí)現(xiàn)代碼(前后端分離)
- php + WebUploader實(shí)現(xiàn)圖片批量上傳功能
相關(guān)文章
jQuery插件zTree實(shí)現(xiàn)獲取一級(jí)節(jié)點(diǎn)數(shù)據(jù)的方法
這篇文章主要介紹了jQuery插件zTree實(shí)現(xiàn)獲取一級(jí)節(jié)點(diǎn)數(shù)據(jù)的方法,結(jié)合實(shí)例形式分析了jQuery插件zTree針對(duì)節(jié)點(diǎn)的遍歷與獲取操作相關(guān)技巧,需要的朋友可以參考下2017-03-03基于jQuery實(shí)現(xiàn)中英文切換導(dǎo)航條效果
這篇文章主要為大家詳細(xì)介紹了基于jQuery實(shí)現(xiàn)中英文切換導(dǎo)航條效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-09-09javascript權(quán)威指南 學(xué)習(xí)筆記之null和undefined
JavaScript中的關(guān)鍵字null是一個(gè)特殊的值,它表示“無(wú)值”。null常常被看作對(duì)象類型的一個(gè)特殊值,即代表“無(wú)對(duì)象”的值。2011-09-0915款優(yōu)秀的jQuery導(dǎo)航菜單插件分享
這篇文章收集了15款優(yōu)秀的jQuery導(dǎo)航菜單插件分享給大家。jQuery 是一個(gè)非常優(yōu)秀的 JavaScript 框架,使用簡(jiǎn)單靈活,同時(shí)還有許多成熟的插件可供選擇,jQuery 讓網(wǎng)站有更好的可用性和用戶體驗(yàn),給訪問(wèn)者對(duì)網(wǎng)站留下非常好的印象。2011-07-07jQuery中event.target和this的區(qū)別詳解
這篇文章主要介紹了jQuery中event.target和this的區(qū)別詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08jquery mobile的觸控點(diǎn)擊事件會(huì)多次觸發(fā)問(wèn)題的解決方法
這篇文章主要介紹了jquery mobile的觸控點(diǎn)擊事件會(huì)多次觸發(fā)問(wèn)題的解決方法以及替代方法,需要的朋友可以參考下2014-05-05使用jQuery和PHP實(shí)現(xiàn)類似360功能開(kāi)關(guān)效果
本文介紹了使用jQuery、PHP和MySQL實(shí)現(xiàn)類似360安全衛(wèi)士防火墻開(kāi)啟關(guān)閉的開(kāi)關(guān),可以將此功能應(yīng)用在產(chǎn)品功能的開(kāi)啟和關(guān)閉功能上,需要的朋友可以參考下2014-02-02