JQuery文件上传插件uploadify在MVC中Session丢失的解决方案

   2023-02-08 学习力0
核心提示:script type="text/javascript"var auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";var ASPSESSID = "@Session.SessionID";$(functi
 

<script type="text/javascript">

    var auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";

    var ASPSESSID = "@Session.SessionID";

    $(function () {

        $("#file_upload").uploadify({

            swf: '/Scripts/uploadify/uploadify.swf',

            uploader: '/Project/File/FileUpload',

            formData: { ASPSESSID: ASPSESSID, AUTHID: auth },

            auto: true,

            …

     });

注意:上面灰底代码很重要!

将下面代码放入Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)

        {

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

        }

 

  

我的uploadify页面

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <link href="../../Content/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
    <script src="../../Content/uploadify/jquery.uploadify.js" type="text/javascript"></script>
    <script src="../../js/jquery.easyui.min.js" type="text/javascript"></script>
    <link href="../../css/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        *
        {
            font-family: "microsoft yahei" , "Times New Roman" , "宋体" , Times, serif;
        }
    </style>
    <script type="text/javascript">
        var auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";
        var ASPSESSID = "@Session.SessionID";
        $(function () {
            $('#uploadify').uploadify({
                // debug: false,             //开启调试
                // successTimeout: 99999,            //超时时间
                formData: {                        //附带值
                    'userid': '用户id',
                    ASPSESSID: ASPSESSID,
                    AUTHID: auth
                },
                // queueID: 'some_file_queue',   //文件选择后的容器ID
                uploader: '/User/UploadUserImg',           // 服务器端处理地址
                swf: '../../Content/uploadify/uploadify.swf',    // 上传使用的 Flash
                width: 130,                          // 按钮的宽度
                height: 25,                         // 按钮的高度
                buttonText: "请选择上传的文件",                 // 按钮上的文字
                buttonCursor: 'hand',              // 按钮的鼠标图标
                fileObjName: 'Filedata',            // 上传参数名称
                // 两个配套使用
                fileTypeExts: "*.jpg;*.png",             // 扩展名
                fileTypeDesc: "请选择 jpg png 文件",     // 文件说明
                auto: false,                // 选择之后,自动开始上传
                multi: false,               // 是否支持同时上传多个文件
                queueSizeLimit: 1,          //设置上传队列中同时允许的上传文件数量 允许多文件上传的时候,同时上传文件的个数
                uploadLimit: 1,                         //uploadLimit:设置允许上传的文件数量,默认为999。
                // removeCompleted: false,   //设置已完成上传的文件是否从队列中移除,默认为true
                onQueueComplete: function (queueData) {//队列中全部文件上传完成时触发事件。
                    alert(queueData.uploadsSuccessful + '个文件上传完成,确认后刷新页面' + queueData.uploadsErrored);
                    window.parent.afterUpdateImg();
                },
                //返回一个错误,选择文件的时候触发
                onSelectError: function (file, errorCode, errorMsg) {
                    alert("error");
                    switch (errorCode) {
                        case -100:
                            alert("上传的文件数量已经超出系统限制的" + $('#uploadify').uploadify('settings', 'queueSizeLimit') + "个文件!");
                            break;
                        case -110:
                            alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#uploadify').uploadify('settings', 'fileSizeLimit') + "大小!");
                            break;
                        case -120:
                            alert("文件 [" + file.name + "] 大小异常!");
                            break;
                        case -130:
                            alert("文件 [" + file.name + "] 类型不正确!");
                            break;
                    }
                },
                onFallback: function () {
                    alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。"); //检测FLASH失败调用
                },
                onUploadSuccess: function (file, data, response) { //上传到服务器,服务器返回相应信息到data里
                }

            });
        });
    </script>
    <title>UploadUserImg</title>
</head>
<body>
    <div>
        <span ></span>
    </div>
    <div>
        <button onclick="javascript:$('#uploadify').uploadify('upload','*');">
            上传图片</button>
        <button onclick="javascript:$('#uploadify').uploadify('cancel', '*');">
            取消上传</button>
    </div>
</body>
</html>

我的global

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Text;
using System.IO;
using System.Web.Security;

namespace BoYaOA
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // 路由名称
                "{controller}/{action}/{id}", // 带有参数的 URL
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // 参数默认值
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            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);
        }
        public void Application_Error()  //Error是管道的事件    也可以从controller类看到   在前面加上Application_ 可以注册方法  放到mvc的GLOBAL
        {
            Exception ex = Server.GetLastError();
            #region Logs
            var fileName = DateTime.Now.ToString("yyyyMMdd") + ".txt";
            var actualLogPath = Server.MapPath("/LogFiles/" + fileName);
            StringBuilder builderLogs = new StringBuilder();
            builderLogs.AppendLine("\r\n");
            builderLogs.AppendLine("------------------------------------" + DateTime.Now.ToString());
            builderLogs.Append(ex.ToString());
            builderLogs.AppendLine("\r\n");
            using (StreamWriter write = new StreamWriter(actualLogPath, true))
            {
                write.Write(builderLogs.ToString());
            }
            #endregion
            //Server.Transfer("/WebError.htm", true);
            //return "error";
        }

    }
}

  

  

 
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • 邮箱自动提示Jquery 插件-实战.失败品
    看到很多 SNS 类网站都有 邮箱注册功能. 参考了一下技术过程,触发事件为 focus keyup 和 后缀 mousedown 事件基本匹配过程就可以完成了. 所以写了下面的代码. 对  万一用户 选择错误.目前很多SNS 站都是要 手动删除后另行选择.我就写一个 focus 替换函数. 
    03-08
  • JQuery——事件绑定bind和on的区别
    引言  通过JQuery对目标对象绑定事件我们大部分都是通过$('选择器').事件名()的形式实现,其实对事件的绑定还可以使用on和bind,为了搞明白两者之间的区别特做记录,以备以后查阅。正文  bind和on都是给元素绑定事件用的,但两者在使用时有些差别,我们最
    03-08
  • jQuery select操作
    获取Select选择的Text和Value:$("#select_id").change(function(){//code...});//为Select添加事件,当选择其中一项时触发var checkText=$("#select_id").find("option:selected").text(); //获取Select选择的Textvar checkValue=$("#select_id").val(); //获
    03-08
  • jquery转盘抽奖活动代码 js大转盘抽奖代码
    jquery转盘抽奖活动代码 js大转盘抽奖代码
    jquery仿各大商城网站圆形转盘抽奖活动,淘宝商城圆形转盘抽奖活动、天猫商城圆形转盘抽奖活动、京东商城圆形转盘抽奖活动等。 查看演示
    03-08
  • jquery仿京东商城商品分类导航菜单 jquery仿京东左侧菜单导航
    jquery仿京东商城商品分类导航菜单 jquery仿京
    jquery hover事件下拉菜单导航仿京东商城商品分类导航样式布局,通过鼠标滑过商品分类导航展示商品分类子菜单内容的效果。 查看演示
    03-08
  • jQuery SuperSlide插件制作72个种常用的网页特效
    jQuery SuperSlide插件制作72个种常用的网页特
    SuperSlide2.1 超级滑动门72个扩展效果 我¥19买的,分享给大家希望大家学会感恩 “什么?20个基础效果+72个扩展效果,做到狗一 样,才19?!太不值了,大爷我给你99!” -- “多谢大爷!” 19元并不贵,就当是对广大互联网默默耕耘者的一点支持与鼓励
    03-08
  • jquery多功能弹出层插件支持Ajax、确认对话框、二次弹出层等
    jquery多功能弹出层插件支持Ajax、确认对话框、
    jquery jBox弹出层插件制作确认对话框弹出层_ajax弹出层_底部浮动弹出层等 查看演示
    03-08
  • jQuery瀑布流实例无限滚动加载图片 瀑布流式页面布局代码
    jQuery瀑布流实例无限滚动加载图片 瀑布流式页
    jquery masonry与infinitescroll两款瀑布流插件制作当下最流行的瀑布流图片展示实例,通过鼠标滚动图片无限加载的类似瀑布的效果的图片展示。用户可以无限浏览图片或内容无限加载瀑布流效果。 查看演示!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transiti
    03-08
  • 17种常用的jQuery全屏焦点图代码 jq 获取焦点
    jQuery全屏焦点图特效制作带标题的焦点图切换代码 jQuery背景和banner图片一起切换全屏焦点图切换代码 jQuery仿音悦台网站全屏带标题的焦点图轮播代码 jQuery响应式焦点图插件制作响应式全屏焦点图切换代码 jquery html5响应式幻灯片插件网站响应式全屏幻
    03-08
  • 6种非常酷炫的jquery banner焦点图片幻灯片切换
    6种非常酷炫的jquery banner焦点图片幻灯片切换
    jquery sequence slide滑动幻灯片插件6款时尚的图片滑动幻灯片切换 查看演示
    03-08
点击排行