解決uploadify使用時(shí)session發(fā)生丟失問題的方法
今天在使用uploadify時(shí)發(fā)現(xiàn)session會(huì)發(fā)生丟失的情況,經(jīng)過一番研究發(fā)現(xiàn),其丟失并不是真正的丟失,而是在使用Flash上傳控件的時(shí)候使用的session機(jī)制和asp.net中的不相同。為解決這個(gè)問題使用兩種方案,下面進(jìn)行介紹
第一種:修改Gobal
前臺(tái)aspx頁(yè)面:
$("#uploadify").uploadify({ 'uploader': '/LZKS/Handler/BigFileUpLoadHandler.ashx', 'swf': '/LZKS/Scripts/uploadify/uploadify.swf', 'cancelImage': '/LZKS/Scripts/uploadify/cancel.png', 'queueID': 'fileQueue', //'auto': false, 'multi': true, 'buttonText': '文件上傳', 'formData': { 'ASPSESSID': ASPSESSID, 'AUTHID': auth }, 'onSelect': function (file) { $('#uploadify').uploadifySettings('formData', { 'ASPSESSID': ASPSESSID, 'AUTHID': auth }); alert(formDate); }, 'onComplete': function (file, data, response) { }, 'onQueueComplete': function () { alert("上傳完成!"); $('#fileQueue').attr('style', 'visibility :hidden'); }, 'onSelectError': function (file, errorCode, errorMsg) { $('#fileQueue').attr('style', 'visibility :hidden'); }, 'onUploadStart': function (file) { $('#fileQueue').attr('style', 'top:200px;left:400px;width:400px;height :400px;visibility :visible'); } }); });
接著修改Gobal中的代碼:
protected void Application_BeginRequest(object sender, EventArgs e) { /* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */ try { string session_param_name = "ASPSESSID"; string session_cookie_name = "ASP.NET_SessionId"; if (HttpContext.Current.Request.Form[session_param_name] != null) { UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]); } else if (HttpContext.Current.Request.QueryString[session_param_name] != null) { UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]); } } catch { } try { string auth_param_name = "AUTHID"; string auth_cookie_name = FormsAuthentication.FormsCookieName; if (HttpContext.Current.Request.Form[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]); } else if (HttpContext.Current.Request.QueryString[auth_param_name] != null) { UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]); } } catch { } } private void UpdateCookie(string cookie_name, string cookie_value) { HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name); if (null == cookie) { cookie = new HttpCookie(cookie_name); } cookie.Value = cookie_value; HttpContext.Current.Request.Cookies.Set(cookie); }
在JS加載前面定義下面兩個(gè)變量
var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>"; var ASPSESSID = "<%= Session.SessionID %>";
Handler文件代碼如下:
public class BigFileUpLoadHandler : IHttpHandler, IRequiresSessionState { DALFile Fdal = new DALFile(); public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; VideoUpLoad(context, CLSOFT.Web.LZKS.Edu.Globe.filename); } public void VideoUpLoad(HttpContext context, string fileFolderName) { context.Response.Charset = "utf-8"; string aaaaaaa=context.Request.QueryString["sessionid"]; HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = HttpContext.Current.Server.MapPath(UploadFileCommon.CreateDir(fileFolderName)); if (file != null) { if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } Model.ModelFile model = new Model.ModelFile(); model.File_ID = Guid.NewGuid().ToString(); model.File_Name = file.FileName; model.File_Path = UploadFileCommon.CreateDir(fileFolderName); model.File_Size = file.ContentLength; model.File_Extension = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1); model.File_Date = DateTime.Now; model.File_CurrentMan = CLSOFT.Web.LZKS.Edu.Globe.name; file.SaveAs(uploadPath + model.File_Name); List<Model.ModelFile> list = null; if (context.Session["File"] == null) { list = new List<Model.ModelFile>(); } else { list = context.Session["File"] as List<Model.ModelFile>; } list.Add(model); context.Session.Add("File", list); } else { context.Response.Write("0"); } }
這段代碼的功能是將多文件的信息存到context.Session["File"] as List<Model.ModelFileModel.ModelFile>為文件信息類 實(shí)現(xiàn)批量上傳的信息給Session
第二種方案:直接向后臺(tái)傳遞session值
Ext.onReady(function () { Ext.QuickTips.init(); <%--JQuery裝載函數(shù)--%> $("#uploadify").uploadify({ 'uploader': '../Uploadify-v2.1.4/uploadify.swf',//上傳swf相對(duì)路徑 'script': '../Service/FileUploadHelper.ashx',//后臺(tái)上傳處理呈現(xiàn) 'cancelImg': '../Uploadify-v2.1.4/cancel.png',//取消上傳按鈕相對(duì)路徑 'checkExisting':true,//服務(wù)端重復(fù)文件檢測(cè) 'folder': '../UploadFile/',//上傳目錄 'fileExt':'*.jpg;*.png;*.gif;*.bmp',//允許上傳的文件格式 'fileDesc':'jpg、png、gif、bmp',//文件選擇時(shí)顯示的提示 'queueID': 'fileQueue',//上傳容器 'auto': false, 'multi': false,//只允許單文件上傳 'buttonText':'Choose File', 'scriptData': { 'name': '', 'type': '','length':'' },//在加載時(shí)此處是null //'onInit':function(){alert("1");},//初始化工作,在Extjs的嵌套中最先觸發(fā)的函數(shù) //選擇一個(gè)文件后觸發(fā) 'onSelect': function(event, queueID, fileObj) { // alert("唯一標(biāo)識(shí):" + queueID + "\r\n" + // "文件名:" + fileObj.name + "\r\n" + // "文件大小:" + fileObj.size + "\r\n" + // "創(chuàng)建時(shí)間:" + fileObj.creationDate + "\r\n" + // "最后修改時(shí)間:" + fileObj.modificationDate + "\r\n" + // "文件類型:" + fileObj.type); $("#uploadify").uploadifySettings("scriptData", { "length": fileObj.size}); //動(dòng)態(tài)更新配(執(zhí)行此處時(shí)可獲得值) }, //上傳單個(gè)文件接收后觸發(fā) 'onComplete': function (event, queueID, fileObj, response, data) { var value = response; if(value==1){ Ext.Msg.alert("提示","上傳成功"); } else if(value==0){ Ext.Msg.alert("提示","請(qǐng)選擇上傳文件"); } else if(value==-1){ Ext.Msg.alert("提示","已存在該文件"); } } }); <%-- jQuery裝載函數(shù)結(jié)束--%>
動(dòng)態(tài)的傳遞參數(shù),并判斷是否合法
//動(dòng)態(tài)加載 function loadFileType(){ //檢測(cè) var medianame=Ext.getCmp("eName").getValue(); if(medianame.trim()==""){ Ext.Msg.alert("提示","媒體名稱不能為空"); return; } var filetype=Ext.getCmp("eType").getValue(); if(filetype=="" || filetype<0){ Ext.Msg.alert("提示","請(qǐng)選擇媒體類型"); return; } //動(dòng)態(tài)更新配(執(zhí)行此處時(shí)可獲得值) $("#uploadify").uploadifySettings("scriptData", { "name": medianame,"type":filetype,"sessionuserid":<%=session_userid %> }); //上傳開始 $('#uploadify').uploadifyUpload(); }
<%=session_userid %>是取后臺(tái)的一個(gè)變量,該變量在加載頁(yè)面的時(shí)候獲得了session值。當(dāng)然也可以在前臺(tái)直接獲得session值。
后臺(tái)處理程序:
public class FileUploadHelper : IRequiresSessionState, IHttpHandler { int nCurrentUserID = -1; public void ProcessRequest(HttpContext context) { try { nCurrentUserID = WebUtil.GetCurrentUserID();//該處的session值得不到 } catch (Exception) { } context.Response.ContentType = "text/plain"; context.Response.Charset = "utf-8"; string strFilename = string.Empty; int nFiletype = 0; float fFilelength = 0; string strFileExt = string.Empty; string strFilePath = string.Empty; if (context.Request["sessionuserid"] != null) { nCurrentUserID = Convert.ToInt32(context.Request["sessionuserid"].ToString()); } if (context.Request["name"] != null)//獲得文件名(動(dòng)態(tài)參數(shù)) { strFilename = context.Request["name"].ToString(); } if (context.Request["type"] != null)//獲得文件類型(動(dòng)態(tài)參數(shù)) { nFiletype = Convert.ToInt32(context.Request["type"].ToString()); } if (context.Request["length"] != null)//獲得文件長(zhǎng)度(動(dòng)態(tài)參數(shù)) { int nEmptFileLength = Convert.ToInt32(context.Request["length"].ToString()); fFilelength = (float)nEmptFileLength / 1024; } if (context.Request["Filename"] != null)//獲得文件名(系統(tǒng)自帶) { string filename = context.Request["Filename"].ToString(); strFileExt = Path.GetExtension(filename).ToLower();//獲得后綴名 } HttpPostedFile file = context.Request.Files["Filedata"]; string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]); //根據(jù)當(dāng)前日期創(chuàng)建一個(gè)文件夾 string dirName = System.DateTime.Now.ToString("yyyyMMdd"); uploadPath += dirName; string tmpRootDir = context.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//獲取程序根目錄 if (file != null) { //判斷目錄是否存在 if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } //判斷文件是否存在 strFilePath = uploadPath + "\\" + strFilename + strFileExt; if (!File.Exists(strFilePath)) { //寫數(shù)據(jù)庫(kù)成功保存文件 Media model = new Media(); int newMediaID = -1; model.media_type = nFiletype; model.media_name = strFilename + strFileExt; model.file_path = strFilePath.Replace(tmpRootDir, "");//保存相對(duì)目錄 model.file_length = fFilelength; newMediaID = MediaBLL.AddMadia(model, nCurrentUserID); if (newMediaID > -1)//數(shù)據(jù)庫(kù)寫入成功 { //保存文件 file.SaveAs(strFilePath); //下面這句代碼缺少的話,上傳成功后上傳隊(duì)列的顯示不會(huì)自動(dòng)消失 context.Response.Write("1"); } } else { context.Response.Write("-1"); } } else { context.Response.Write("0"); } }
這樣就可以解決該問題了。
希望這兩種方法都能幫助大家順利解決session丟失問題,謝謝大家的閱讀。
- C# SESSION丟失問題的解決辦法
- Yii框架用戶登錄session丟失問題解決方法
- php頁(yè)面跳轉(zhuǎn)session cookie丟失導(dǎo)致不能登錄等問題的解決方法
- Session 失效的原因匯總及解決丟失辦法
- Windows下Apache + PHP SESSION丟失的解決過程全紀(jì)錄
- Session丟失的解決辦法小結(jié)
- iis7中session丟失的解決方法小結(jié)
- uploadify在Firefox下丟失session問題的解決方法
- ASP.NET在IE10中無法判斷用戶已登入及Session丟失問題解決方法
- 解決window.location.href之后session丟失的問題
相關(guān)文章
.NetCore使用ImageSharp進(jìn)行圖片的生成
ImageSharp是對(duì)NetCore平臺(tái)擴(kuò)展的一個(gè)圖像處理方案,以往網(wǎng)上的案例多以生成文字及畫出簡(jiǎn)單圖形、驗(yàn)證碼等方式進(jìn)行探討和實(shí)踐,今天我分享一下所在公司項(xiàng)目的實(shí)際應(yīng)用案例,導(dǎo)出微信二維碼圖片,圓形頭像,感興趣的朋友一起看看吧2022-06-06AspNetPager與Socut.Data使用實(shí)例代碼
最近對(duì)AspNetPager與Socut.Data這兩個(gè)控件產(chǎn)生了濃厚的興趣,這兩個(gè)控件配合可以減輕很多程序員編寫代碼的壓力。ASpNetPager為分頁(yè)控件,而Socut.Data為數(shù)據(jù)操作控件,ACCESS,MSSQL都可以。2008-07-07ASP.NET MVC3網(wǎng)站創(chuàng)建與發(fā)布(1)
這篇文章主要介紹了ASP.NET MVC3網(wǎng)站創(chuàng)建與發(fā)布,根據(jù)文章內(nèi)容大家可以實(shí)現(xiàn)發(fā)布網(wǎng)站,感興趣的小伙伴們可以參考一下2015-08-08.NET微信公眾號(hào)開發(fā)之公眾號(hào)消息處理
本文給大家講述的是在.net微信公眾號(hào)開發(fā)中的公眾號(hào)的消息處理的相關(guān)內(nèi)容,非常詳細(xì),有需要的小伙伴可以參考下。2015-07-07詳解免費(fèi)開源的DotNet二維碼操作組件ThoughtWorks.QRCode(.NET組件介紹之四)
本篇文章主要介紹了免費(fèi)開源的DotNet二維碼操作組件ThoughtWorks.QRCode,非常具有實(shí)用價(jià)值,有興趣的同學(xué)可以來了解一下。2016-12-12ASP.NET設(shè)計(jì)網(wǎng)絡(luò)硬盤之兩重要類代碼
要進(jìn)行“網(wǎng)絡(luò)硬盤”功能設(shè)計(jì),首先要熟悉.NET中處理文件和文件夾的操作。File類和Directory類是其中最主要的兩個(gè)類。了解它們將對(duì)后面功能的實(shí)現(xiàn)提供很大的便利2012-10-10