双核浏览器下在chrome内核中使用uploadify总有302问题,也不知道如何修复,之所以喜欢360浏览器是因为帮客户控制渲染内核:
若页面需默认用极速核,增加标签:<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,就是一个成熟的解决方案了。
先看前端,我们将最常用的操作封装为插件,asp.net中和MVC中最好使用相对于应用程序的绝对路径,自行定义全局applicationPath :var applicationPath = "@(Href("~")=="/"?"":Href("~"))";
前端插件代码:
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后使用:
$("#uploader").powerWebUpload({ hiddenInputId: "uploadhidden" });
html端需要一个容器和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的数据,文件在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"); } }
}
----
一开始发首页被退下来了,现在重新编辑使内容更加完整,优化了插件代码
完整demo: http://yunpan.cn/cgifFwGhbGSvi 提取码 f7c1
补充:
扩展自定义参数,利用uploadBeforeSend事件可以扩展参数,插件内可根据需要修改。
cookie的问题,我用微软自带的登录系统,不需要做任何特殊处理完全没有问题。