欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-11 19:24:16
今天在使用uploadify时发现session会发生丢失的情况,经过一番研究发现,其丢失并不是真正的丢失,而是在使用flash上传控件的时候使用的session机制和as...

今天在使用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丢失问题,谢谢大家的阅读。

上一篇:

下一篇: