Solving the problem of session loss during uploadify use-practical tips

Source: Internet
Author: User
Tags auth datetime httpcontext session id relative save file unique id visibility

Today in the use of uploadify found session will be lost, after a study found that its loss is not really lost, but in the use of Flash upload control when using the session mechanism and the asp.net in the different. Two scenarios are used to address this problem, as described below

First Type: Modify Gobal
foreground aspx page:

$ ("#uploadify"). Uploadify ({' Uploader ': '/lzks/handler/bigfileuploadhandler.ashx ', ' swf ': '/lzks/script  
        S/uploadify/uploadify.swf ', ' cancelimage ': '/lzks/scripts/uploadify/cancel.png ', ' Queueid ': ' FileQueue ', ' Auto ': false, ' multi ': true, ' buttontext ': ' File Upload ', ' formData ': {' aspsessid ': ASPS  Essid, ' Authid ': auth}, ' onselect ': function (file) {$ (' #uploadify '). Uploadifysettings (' FormData ', { 
          ' Aspsessid ': aspsessid, ' Authid ': auth}); 
        alert (formdate); 
          }, ' OnComplete ': function (file, data, response) {}, ' Onqueuecomplete ': function () { Alert ("Upload complete!") 
          "); 
        $ (' #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 '); 
    } 
      }); 
 });

The

Then modifies the code in Gobal:

protected void Application_BeginRequest (object sender, EventArgs e) {/* We guess at the ' point ' session is no T already retrieved by application so we recreate cookies with the session ID ... */try {string ses 
        Sion_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) {Updatecooki 
        E (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 (a 
        Uth_cookie_name, Httpcontext.current.request.querystring[auth_param_name]); } catch {}} private void Updatecookie (String cookie_name, String Cookie_valu 
      e) {HttpCookie cookie = HttpContext.Current.Request.Cookies.Get (cookie_name); 
      if (null = = cookie) {cookie = new HttpCookie (cookie_name); } cookies. 
      Value = Cookie_value; 
    HttpContext.Current.Request.Cookies.Set (cookie); 
 }

Define the following two variables before JS load

var auth = "<% = request.cookies[formsauthentication.formscookiename]==null?" String. Empty:request.cookies[formsauthentication.formscookiename]. Value%> "; 
 var aspsessid = "<%= session.sessionid%>"; 

The handler file code is as follows:

 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"); 
 }  
    }

The function of this code is to save the information of multiple files to the context. session["File" as list<model.modelfilemodel.modelfile> for file information class   Implementation of bulk upload information to session 
The second scenario: pass the session value directly to the background

Ext.onready (function () {Ext.QuickTips.init (); <%--jquery load function--%> $ ("#uploadify"). Uploadify ({' uploader ': ' ...) /uploadify-v2.1.4/uploadify.swf ',//upload swf relative path ' script ': '. /service/fileuploadhelper.ashx ',//background upload processing presents ' cancelimg ': '. /uploadify-v2.1.4/cancel.png ',//Cancel Upload button relative path ' checkexisting ': true,//server-side duplicate file Detection ' folder ': '. /uploadfile/',//upload directory ' fileext ': ' *.jpg;*.png;*.gif;*.bmp ',//Allow uploaded file format ' filedesc ': ' jpg, PNG, GIF, BMP ',//File selection Prompt ' Queueid ': ' Filequeue ',//upload container ' auto ': false, ' multi ': false,//only allow single file upload ' Buttont Ext ': ' Choose File ', ' scriptdata ': {' name ': ', ' type ': ', ' length ': '},//is null//' OnInit ' at load: functi 
On () {alert ("1");},//initialization, triggering the first function in ExtJS's nesting///Selecting a file Triggers ' onselect ': function (event, Queueid, Fileobj) { Alert ("Unique ID:" + queueid + "\ r \ n" +//"FileName:" + fileobj.name + "\ r \ n" +//"File size:" + Fileo Bj.siZe + "\ r \ n" +//"Create Time:" + fileobj.creationdate + "\ r \ n" +//"Last modified:" + Fileobj.modificationdate + " 
           \ r \ n "+//" file type: + Fileobj.type); $ ("#uploadify"). Uploadifysettings ("Scriptdata", {"Length": fileobj.size}); Dynamic update match (available when executing here)},//upload a single file to trigger ' OnComplete ' after receiving: function (event, Queueid, Fileobj, response, 
           Data) {var value = response; 
           if (value==1) {Ext.Msg.alert ("hint", "upload successful"); 
           else if (value==0) {Ext.Msg.alert ("prompt", "Please select Upload file"); 
           else if (value==-1) {Ext.Msg.alert ("hint", "The file already exists"); 
    } 
            
         } 
      }); 
 <%--jquery load function End--%>

Dynamically passing parameters and judging whether it's legal

Dynamic load 
  function Loadfiletype () { 
  //detect 
  var medianame=ext.getcmp ("Ename"). GetValue (); 
  if (medianame.trim () = = "") { 
    Ext.Msg.alert ("Hint", "Media name cannot be blank"); 
    return; 
  } 
  var filetype=ext.getcmp ("EType"). GetValue (); 
  if (filetype== "| | | filetype<0) { 
    Ext.Msg.alert (" Hint "," Select media Type "); 
    return; 
  } 
  Dynamic update matching (value available when executing here) 
  $ ("#uploadify"). Uploadifysettings ("Scriptdata", {"name": MediaName, "type": filetype, " Sessionuserid ": <%=session_userid%>}); 
  Upload start 
  $ (' #uploadify '). Uploadifyupload (); 
     

<%=session_userid%> is a variable that takes the background and gets the session value when the page is loaded. Of course, you can get the session value directly from the foreground.
Background handler:

public class Fileuploadhelper:irequiressessionstate, IHttpHandler {int ncurrentuserid =-1; public void ProcessRequest (HttpContext context) {try {Ncurrentuserid = Webutil.getcurrentuserid ();/ The session's session is worth less than the} 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)//get filename (dynamic parameter) {strFileName = context. request["Name"]. 
    ToString (); } if (context. request["type"]!= null)//Get file type (dynamic parameter) {Nfiletype = Convert.ToInt32 (context. request["type"]. 
    ToString ()); } if (context. request["LengtH "]!= null)//Get file Length (dynamic parameters) {int nemptfilelength = Convert.ToInt32 (context. request["Length"]. 
      ToString ()); 
    Ffilelength = (float) nemptfilelength/1024; } if (context. request["filename"]!= null)//get filename (System from) {string filename = context. request["Filename"]. 
      ToString (); Strfileext = path.getextension (filename). ToLower ()//Get suffix name} httppostedfile file = context. 
    request.files["Filedata"]; String uploadpath = HttpContext.Current.Server.MapPath (@context. 
    request["folder"]); 
    Create a folder from the current date string dirname = System.DateTime.Now.ToString ("YyyyMMdd"); 
 
    Uploadpath + = dirname; String Tmprootdir = context. 
    Server.MapPath (System.Web.HttpContext.Current.Request.ApplicationPath.ToString ())//Get program root if (file!= null) {//To determine if the directory exists if (! 
      Directory.Exists (Uploadpath)) {directory.createdirectory (Uploadpath); //Determine if the file exists strFilePath = Uploadpath + "\" + strFileName + Strfileext; if (! 
        File.exists (strFilePath)) {//write database successfully saved the file media model = new Media (); 
        int newmediaid =-1; 
        Model.media_type = Nfiletype; 
        Model.media_name = strFileName + strfileext; 
        Model.file_path = Strfilepath.replace (Tmprootdir, "");//Save relative directory model.file_length = ffilelength; 
        Newmediaid = Mediabll.addmadia (model, Ncurrentuserid); if (Newmediaid > 1)//database Write succeeded {//save file files. 
          SaveAs (strFilePath); The following code is missing, upload the queue after the success of the display will not automatically disappear the context. 
        Response.Write ("1"); } else {context. 
      Response.Write ("-1"); } else {context. 
    Response.Write ("0"); 
 } 
  }

This will solve the problem.

I hope both of these methods can help us to solve the problem of session loss, thank you for your reading.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.