侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

解决uploadify使用时session发生丢失问题的方法

技术  /  管理员 发布于 7年前   136

今天在使用uploadify时发现session会发生丢失的情况,经过一番研究发现,其丢失并不是真正的丢失,而是在使用Flash上传控件的时候使用的session机制和asp.net中的不相同。为解决这个问题使用两种方案,下面进行介绍

第一种:修改Gobal
前台aspx页面:

$("#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加载前面定义下面两个变量

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>为文件信息类 实现批量上传的信息给Session 
第二种方案:直接向后台传递session值

Ext.onReady(function () {     Ext.QuickTips.init();     <%--JQuery装载函数--%>       $("#uploadify").uploadify({         'uploader': '../Uploadify-v2.1.4/uploadify.swf',//上传swf相对路径         'script': '../Service/FileUploadHelper.ashx',//后台上传处理呈现         'cancelImg': '../Uploadify-v2.1.4/cancel.png',//取消上传按钮相对路径         'checkExisting':true,//服务端重复文件检测         'folder': '../UploadFile/',//上传目录         'fileExt':'*.jpg;*.png;*.gif;*.bmp',//允许上传的文件格式         'fileDesc':'jpg、png、gif、bmp',//文件选择时显示的提示         'queueID': 'fileQueue',//上传容器         'auto': false,         'multi': false,//只允许单文件上传         'buttonText':'Choose File',         'scriptData': { 'name': '', 'type': '','length':'' },//在加载时此处是null         //'onInit':function(){alert("1");},//初始化工作,在Extjs的嵌套中最先触发的函数         //选择一个文件后触发         'onSelect': function(event, queueID, fileObj) { //          alert("唯一标识:" + queueID + "\r\n" + //          "文件名:" + fileObj.name + "\r\n" + //          "文件大小:" + fileObj.size + "\r\n" + //          "创建时间:" + fileObj.creationDate + "\r\n" + //          "最后修改时间:" + fileObj.modificationDate + "\r\n" + //          "文件类型:" + fileObj.type);$("#uploadify").uploadifySettings("scriptData", { "length": fileObj.size}); //动态更新配(执行此处时可获得值)         },         //上传单个文件接收后触发         'onComplete': function (event, queueID, fileObj, response, data) {var value = response;if(value==1){Ext.Msg.alert("提示","上传成功");}else if(value==0){Ext.Msg.alert("提示","请选择上传文件");}else if(value==-1){ Ext.Msg.alert("提示","已存在该文件");}          }       });     <%-- jQuery装载函数结束--%> 

动态的传递参数,并判断是否合法

//动态加载   function loadFileType(){   //检测   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("提示","请选择媒体类型");     return;   }   //动态更新配(执行此处时可获得值)   $("#uploadify").uploadifySettings("scriptData", { "name": medianame,"type":filetype,"sessionuserid":<%=session_userid %> });   //上传开始   $('#uploadify').uploadifyUpload();   }   

<%=session_userid %>是取后台的一个变量,该变量在加载页面的时候获得了session值。当然也可以在前台直接获得session值。 
后台处理程序:

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)//获得文件名(动态参数)     {       strFilename = context.Request["name"].ToString();     }     if (context.Request["type"] != null)//获得文件类型(动态参数)     {       nFiletype = Convert.ToInt32(context.Request["type"].ToString());     }     if (context.Request["length"] != null)//获得文件长度(动态参数)     {       int nEmptFileLength = Convert.ToInt32(context.Request["length"].ToString());       fFilelength = (float)nEmptFileLength / 1024;     }     if (context.Request["Filename"] != null)//获得文件名(系统自带)     {       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"]);     //根据当前日期创建一个文件夹     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))       {         //写数据库成功保存文件         Media model = new Media();         int newMediaID = -1;         model.media_type = nFiletype;         model.media_name = strFilename + strFileExt;         model.file_path = strFilePath.Replace(tmpRootDir, "");//保存相对目录         model.file_length = fFilelength;         newMediaID = MediaBLL.AddMadia(model, nCurrentUserID);         if (newMediaID > -1)//数据库写入成功         {           //保存文件           file.SaveAs(strFilePath);           //下面这句代码缺少的话,上传成功后上传队列的显示不会自动消失           context.Response.Write("1");         }       }       else       {         context.Response.Write("-1");       }     }     else     {       context.Response.Write("0");     }   } 

这样就可以解决该问题了。

希望这两种方法都能帮助大家顺利解决session丢失问题,谢谢大家的阅读。


  • 上一条:
    解决Visual Studio 2012 Update 4 RC启动调试失败的方案
    下一条:
    GridView中日期不显示时分秒的完美解决方法
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 2024.07.09日OpenAI将终止对中国等国家和地区API服务(0个评论)
    • 2024/6/9最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 国外服务器实现api.openai.com反代nginx配置(0个评论)
    • 2024/4/28最新免费公益节点SSR/V2ray/Shadowrocket/Clash节点分享|科学上网|免费梯子(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2017-07
    • 2017-08
    • 2017-09
    • 2018-01
    • 2018-07
    • 2018-08
    • 2018-09
    • 2018-12
    • 2019-01
    • 2019-02
    • 2019-03
    • 2019-04
    • 2019-05
    • 2019-06
    • 2019-07
    • 2019-08
    • 2019-09
    • 2019-10
    • 2019-11
    • 2019-12
    • 2020-01
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2020-10
    • 2020-11
    • 2021-04
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-09
    • 2021-10
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-12
    • 2024-02
    • 2024-04
    • 2024-05
    • 2024-06
    • 2025-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客