雙核瀏覽器下在chrome內核中使用uploadify總有302問題,也不知道如何修復,之因此喜歡360瀏覽器是由於幫客戶控制渲染內核:css
若頁面需默認用極速核,增長標籤:<meta name="renderer" content="webkit"/> 若頁面需默認用ie兼容內核,增長標籤:<meta name="renderer" content="ie-comp"/> 若頁面需默認用ie標準內核,增長標籤:<meta name="renderer" content="ie-stand"/>
要解決302問題也很簡單,就是html5的文件上傳,正好最近在ueditor裏看到百度的webuploader,會自動選擇flash html5,就是一個成熟的解決方案了。html
先看前端,咱們將最經常使用的操做封裝爲插件,asp.net中和MVC中最好使用相對於應用程序的絕對路徑,自行定義全局applicationPath :var applicationPath = "@(Href("~")=="/"?"":Href("~"))"; 前端
前端插件代碼:html5
1 (function ($, window) { 2 var applicationPath = window.applicationPath === "" ? "" : window.applicationPath || "../.."; 3 function S4() { 4 return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); 5 } 6 7 function initWebUpload(item, options) { 8 9 if (!WebUploader.Uploader.support()) { 10 var error = "上傳控件不支持您的瀏覽器!請嘗試升級flash版本或者使用Chrome引擎的瀏覽器。<a target='_blank' href='http://se.360.cn'>下載頁面</a>"; 11 if (window.console) { 12 window.console.log(error); 13 } 14 $(item).text(error); 15 return; 16 } 17 18 var defaults = { 19 hiddenInputId: "uploadifyHiddenInputId", // input hidden id 20 onAllComplete: function (event) { }, // 當全部file都上傳後執行的回調函數 21 onComplete: function (event) { },// 每上傳一個file的回調函數 22 innerOptions: {}, 23 fileNumLimit: undefined, 24 fileSizeLimit: undefined, 25 fileSingleSizeLimit: undefined, 26 PostbackHold: false 27 }; 28 29 var opts = $.extend({}, defaults, options); 30 var hdFileData = $("#" + opts.hiddenInputId); 31 32 var target = $(item);//容器 33 var pickerid = ""; 34 if (typeof guidGenerator36 != 'undefined')//給一個惟一ID 35 pickerid = guidGenerator36(); 36 else 37 pickerid = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); 38 39 var uploaderStrdiv = '<div class="webuploader">' + 40 '<div id="thelist" class="uploader-list"></div>' + 41 '<div class="btns">' + 42 '<div id="' + pickerid + '">選擇文件</div>' + 43 //'<a id="ctlBtn" class="btn btn-default">開始上傳</a>' + 44 '</div>' + 45 '</div>'; 46 target.append(uploaderStrdiv); 47 48 var $list = target.find('#thelist'), 49 $btn = target.find('#ctlBtn'),//這個留着,以便隨時切換是否要手動上傳 50 state = 'pending', 51 uploader; 52 53 var jsonData = { 54 fileList: [] 55 }; 56 57 var webuploaderoptions = $.extend({ 58 59 // swf文件路徑 60 swf: applicationPath + '/Scripts/lib/webuploader/Uploader.swf', 61 62 // 文件接收服務端。 63 server: applicationPath + '/MvcPages/WebUploader/Process', 64 65 // 選擇文件的按鈕。可選。 66 // 內部根據當前運行是建立,多是input元素,也多是flash. 67 pick: '#' + pickerid, 68 69 // 不壓縮image, 默認若是是jpeg,文件上傳前會壓縮一把再上傳! 70 resize: false, 71 fileNumLimit: opts.fileNumLimit, 72 fileSizeLimit: opts.fileSizeLimit, 73 fileSingleSizeLimit: opts.fileSingleSizeLimit 74 }, 75 opts.innerOptions); 76 var uploader = WebUploader.create(webuploaderoptions); 77 78 //回發時還原hiddenfiled的保持數據 79 var fileDataStr = hdFileData.val(); 80 if (fileDataStr && opts.PostbackHold) { 81 jsonData = JSON.parse(fileDataStr); 82 $.each(jsonData.fileList, function (index, fileData) { 83 var newid = S4(); 84 fileData.queueId = newid; 85 $list.append('<div id="' + newid + '" class="item">' + 86 '<div class="info">' + fileData.name + '</div>' + 87 '<div class="state">已上傳</div>' + 88 '<div class="del"></div>' + 89 '</div>'); 90 }); 91 hdFileData.val(JSON.stringify(jsonData)); 92 } 93 94 95 96 97 uploader.on('fileQueued', function (file) {//隊列事件 98 $list.append('<div id="' + file.id + '" class="item">' + 99 '<div class="info">' + file.name + '</div>' + 100 '<div class="state">等待上傳...</div>' + 101 '<div class="del"></div>' + 102 '</div>'); 103 }); 104 uploader.on('uploadProgress', function (file, percentage) {//進度條事件 105 var $li = target.find('#' + file.id), 106 $percent = $li.find('.progress .bar'); 107 108 // 避免重複建立 109 if (!$percent.length) { 110 $percent = $('<span class="progress">' + 111 '<span class="percentage"><span class="text"></span>' + 112 '<span class="bar" role="progressbar" style="width: 0%">' + 113 '</span></span>' + 114 '</span>').appendTo($li).find('.bar'); 115 } 116 117 $li.find('div.state').text('上傳中'); 118 $li.find(".text").text(Math.round(percentage * 100) + '%'); 119 $percent.css('width', percentage * 100 + '%'); 120 }); 121 uploader.on('uploadSuccess', function (file, response) {//上傳成功事件 122 target.find('#' + file.id).find('div.state').text('已上傳'); 123 var fileEvent = { 124 queueId: file.id, 125 name: file.name, 126 size: file.size, 127 type: file.type, 128 filePath: response.filePath 129 }; 130 jsonData.fileList.push(fileEvent) 131 opts.onComplete(fileEvent); 132 133 }); 134 135 uploader.on('uploadError', function (file) { 136 target.find('#' + file.id).find('div.state').text('上傳出錯'); 137 }); 138 139 uploader.on('uploadComplete', function (file) {//所有完成事件 140 target.find('#' + file.id).find('.progress').fadeOut(); 141 var fp = $("#" + opts.hiddenInputId); 142 fp.val(JSON.stringify(jsonData)); 143 opts.onAllComplete(jsonData.fileList); 144 }); 145 146 uploader.on('fileQueued', function (file) { 147 uploader.upload(); 148 }); 149 150 uploader.on('filesQueued', function (file) { 151 uploader.upload(); 152 }); 153 154 uploader.on('all', function (type) { 155 if (type === 'startUpload') { 156 state = 'uploading'; 157 } else if (type === 'stopUpload') { 158 state = 'paused'; 159 } else if (type === 'uploadFinished') { 160 state = 'done'; 161 } 162 163 if (state === 'uploading') { 164 $btn.text('暫停上傳'); 165 } else { 166 $btn.text('開始上傳'); 167 } 168 }); 169 170 $btn.on('click', function () { 171 if (state === 'uploading') { 172 uploader.stop(); 173 } else { 174 uploader.upload(); 175 } 176 }); 177 //刪除 178 $list.on("click", ".del", function () { 179 var $ele = $(this); 180 var id = $ele.parent().attr("id"); 181 var deletefile = {}; 182 $.each(jsonData.fileList, function (index, item) { 183 if (item && item.queueId === id) {
uploader.removeFile(uploader.getFile(id));//不要遺漏 184 deletefile = jsonData.fileList.splice(index, 1)[0]; 185 $("#" + opts.hiddenInputId).val(JSON.stringify(jsonData)); 186 $.post(applicationi + "/Webploader/Delete", { 'filepathname': deletefile.filePath }, function (returndata) { 187 $ele.parent().remove(); 188 }); 189 return; 190 } 191 }); 192 }); 193 194 } 195 196 197 $.fn.powerWebUpload = function (options) { 198 var ele = this; 199 if (typeof PowerJs != 'undefined') { 200 $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.css", function () { }, 'css'); 201 $.lazyLoad(applicationPath + "/Scripts/lib/webuploader/webuploader.min.js", function () { 202 initWebUpload(ele, options); 203 }); 204 } 205 else { 206 initWebUpload(ele, options); 207 } 208 } 209 })(jQuery, window);
頁面引入上述js後使用:git
$("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" }); github
html端須要一個容器和hiddenweb
<div id="uploader"></div> <asp:HiddenField ID="hfFilePath" ClientIDMode="Static" runat="server" />
MVC版後端文件接收,即使你是asp.net 引入mvc作ajax也是能夠的: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的數據,文件在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"); } //爲了安全 檢查一下路徑 不夠嚴謹 自行更具業務作更加細緻的判斷 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"); } }
}
----chrome
一開始發首頁被退下來了,如今從新編輯使內容更加完整,優化了插件代碼json
完整demo: http://yunpan.cn/cgifFwGhbGSvi 提取碼 f7c1
https://github.com/gxrsprite/AspnetMvcWebuploaderDemo
補充:
擴展自定義參數,利用uploadBeforeSend事件能夠擴展參數,插件內可根據須要修改。
cookie的問題,我用微軟自帶的登陸系統,不須要作任何特殊處理徹底沒有問題。