MVC使用uploadify3.1 IE下正常 firefox、chrome出现HTTPERROR 302错误解决办法
jquery uploadify在ie下可以正常上传,在实现异步上传的时候,每一个文件在上传时都会提交给服务器一个请求。每个请求都需要安全验证,session 和cookie的校验。是的,就是这样。由于jquery uploadify是借助flash来实现上传的,每一次向后台发送数据流请求时,ie会自动把本地cookie存储捆绑在一起发送给服务器。但 firefox、chrome不会这样做,他们会认为这样不安全。
首先需要对global.asxa添加如下内容
1 protected void Application_BeginRequest(object sender, EventArgs e) 2 { 3 /* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */ 4 try 5 { 6 string session_param_name = "ASPSESSID"; 7 string session_cookie_name = "ASP.NET_SessionId"; 8 9 if (HttpContext.Current.Request.Form[session_param_name] != null) 10 { 11 UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]); 12 } 13 else if (HttpContext.Current.Request.QueryString[session_param_name] != null) 14 { 15 UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]); 16 } 17 } 18 catch 19 { 20 } 21 22 try 23 { 24 string auth_param_name = "AUTHID"; 25 string auth_cookie_name = FormsAuthentication.FormsCookieName; 26 27 if (HttpContext.Current.Request.Form[auth_param_name] != null) 28 { 29 UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]); 30 } 31 else if (HttpContext.Current.Request.QueryString[auth_param_name] != null) 32 { 33 UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]); 34 } 35 36 } 37 catch 38 { 39 } 40 } 41 42 private void UpdateCookie(string cookie_name, string cookie_value) 43 { 44 HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name); 45 if (null == cookie) 46 { 47 cookie = new HttpCookie(cookie_name); 48 } 49 cookie.Value = cookie_value; 50 HttpContext.Current.Request.Cookies.Set(cookie); 51 }
初始化页面上传插件代码如下
1 <script type="text/javascript"> 2 var auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)"; 3 var ASPSESSID = "@Session.SessionID"; 4 5 $(function () { 6 $('#upload').uploadify({ 7 'formData': { 'folder': '/Upload', 'ASPSESSID': ASPSESSID, 'AUTHID': auth }, 8 'buttonText': '浏览', 9 'buttonClass': 'browser', 10 'fileSizeLimit' : '100KB', 11 'fileTypeExts': '*.xls;*.xlsx', 12 'removeCompleted': false, 13 'swf': '@Url.Content("~/Scripts/Uploadify/uploadify.swf")', 14 'uploader': '/Upload', 15 'onUploadSuccess': function (file, data, response) {} 16 }); 17 }); 18 </script>