Method to solve the problem of session missing when uploadify is used
- 2021-07-24 10:40:28
- OfStack
Today, when using uploadify, it is found that session will be lost. After a study, it is found that its loss is not really lost, but the session mechanism used when uploading controls using Flash is different from that in asp. net. There are two solutions to solve this problem, which are described below
Type 1: Modify Gobal
Foreground aspx page:
$("#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': ' File upload ',
'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(" 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');
}
});
});
Then modify the code in 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);
}
Define the following two variables before JS loading
var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";
var ASPSESSID = "<%= Session.SessionID %>";
The code for the Handler file 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 store multi-file information to context. Session ["File"] as List
<
Model.ModelFileModel.ModelFile
>
Realize batch uploading information for file information class to Session
Scenario 2: Pass the session value directly to the background
Ext.onReady(function () {
Ext.QuickTips.init();
<%--JQuery Loading function --%>
$("#uploadify").uploadify({
'uploader': '../Uploadify-v2.1.4/uploadify.swf',// Upload swf Relative path
'script': '../Service/FileUploadHelper.ashx',// Background upload processing presentation
'cancelImg': '../Uploadify-v2.1.4/cancel.png',// Relative path of unupload button
'checkExisting':true,// Server-side duplicate file detection
'folder': '../UploadFile/',// Upload directory
'fileExt':'*.jpg;*.png;*.gif;*.bmp',// File formats allowed for uploading
'fileDesc':'jpg , png , gif , bmp',// Prompt for file selection
'queueID': 'fileQueue',// Upload container
'auto': false,
'multi': false,// Only single file uploads are allowed
'buttonText':'Choose File',
'scriptData': { 'name': '', 'type': '','length':'' },// At load time, this is null
//'onInit':function(){alert("1");},// Initialize the work, in the Extjs The function triggered first in the nesting of
// Select 1 Triggered after 1 file
'onSelect': function(event, queueID, fileObj) {
// alert(" Only 1 Identification :" + queueID + "\r\n" +
// " Filename: " + fileObj.name + "\r\n" +
// " File size: " + fileObj.size + "\r\n" +
// " Creation time: " + fileObj.creationDate + "\r\n" +
// " Last modified time: " + fileObj.modificationDate + "\r\n" +
// " File type: " + fileObj.type);
$("#uploadify").uploadifySettings("scriptData", { "length": fileObj.size}); // Dynamic update allocation ( Values are available when executing here )
},
// Triggered after uploading a single file
'onComplete': function (event, queueID, fileObj, response, data) {
var value = response;
if(value==1){
Ext.Msg.alert(" Prompt "," Upload succeeded ");
}
else if(value==0){
Ext.Msg.alert(" Prompt "," Please select Upload File ");
}
else if(value==-1){
Ext.Msg.alert(" Prompt "," The file already exists ");
}
}
});
<%-- jQuery End of loading function --%>
Dynamic transfer parameters and judge whether it is legal or not
// Dynamic loading
function loadFileType(){
// Detection
var medianame=Ext.getCmp("eName").getValue();
if(medianame.trim()==""){
Ext.Msg.alert(" Prompt "," Media name cannot be empty ");
return;
}
var filetype=Ext.getCmp("eType").getValue();
if(filetype=="" || filetype<0){
Ext.Msg.alert(" Prompt "," Please select a media type ");
return;
}
// Dynamic update allocation ( Values are available when executing here )
$("#uploadify").uploadifySettings("scriptData", { "name": medianame,"type":filetype,"sessionuserid":<%=session_userid %> });
// Upload start
$('#uploadify').uploadifyUpload();
}
<
%=session_userid %
>
It is a variable in the background, which gets the session value when loading the page. Of course, the session value can also be obtained directly from the foreground.
Spooler:
public class FileUploadHelper : IRequiresSessionState, IHttpHandler
{
int nCurrentUserID = -1;
public void ProcessRequest(HttpContext context)
{
try
{
nCurrentUserID = WebUtil.GetCurrentUserID();// That's session Not worth it
}
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 the file name ( Dynamic parameter )
{
strFilename = context.Request["name"].ToString();
}
if (context.Request["type"] != null)// Get the file type (dynamic parameter)
{
nFiletype = Convert.ToInt32(context.Request["type"].ToString());
}
if (context.Request["length"] != null)// Get the file length (dynamic parameter)
{
int nEmptFileLength = Convert.ToInt32(context.Request["length"].ToString());
fFilelength = (float)nEmptFileLength / 1024;
}
if (context.Request["Filename"] != null)// Get the file name (come with the system)
{
string filename = context.Request["Filename"].ToString();
strFileExt = Path.GetExtension(filename).ToLower();// Get the suffix name
}
HttpPostedFile file = context.Request.Files["Filedata"];
string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"]);
// Based on the current date 1 Folders
string dirName = System.DateTime.Now.ToString("yyyyMMdd");
uploadPath += dirName;
string tmpRootDir = context.Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());// Get the program root directory
if (file != null)
{
// Determine whether the directory exists
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
// Determine whether the file exists
strFilePath = uploadPath + "\\" + strFilename + strFileExt;
if (!File.Exists(strFilePath))
{
// Write to the database and save the file successfully
Media model = new Media();
int newMediaID = -1;
model.media_type = nFiletype;
model.media_name = strFilename + strFileExt;
model.file_path = strFilePath.Replace(tmpRootDir, "");// Save relative directories
model.file_length = fFilelength;
newMediaID = MediaBLL.AddMadia(model, nCurrentUserID);
if (newMediaID > -1)// Database write successful
{
// Save a file
file.SaveAs(strFilePath);
// If the following code is missing, the display of the upload queue will not disappear automatically after the upload is successful
context.Response.Write("1");
}
}
else
{
context.Response.Write("-1");
}
}
else
{
context.Response.Write("0");
}
}
In this way, the problem can be solved.
I hope these two methods can help you solve the problem of session loss smoothly. Thank you for reading.