MVC中使用jquery uploadify上傳圖片報302錯誤

來源:互聯網
上載者:User

標籤:

使用jquery uploadify上傳圖片報302錯誤研究了半天,發現我上傳的action中有根據session判斷使用者是否登入,如果沒有登入就跳到登陸頁,所以就出現了302跳轉錯誤。原來更新了flash的版本以後,通過uploadify擷取不到session的值。我目前的解決辦法是:

Global.asax.cs中:

     /// <summary>        /// 解決uploadif上傳無法擷取Cookie的情況        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void Application_BeginRequest(object sender, EventArgs e)        {            try            {                HttpRequest request = HttpContext.Current.Request;                foreach (string k in request.Form.Keys)                {                    if (k.IndexOf("cookie_") >= 0)                        AppendingCookies(k.Remove(0, 7), request.Form[k], request);                }            }            catch { }        }        private void AppendingCookies(string cookieName, string cookieValue, HttpRequest request)        {            HttpCookie hc = request.Cookies.Get(cookieName);            if (null == hc)                hc = new HttpCookie(cookieName);            hc.Value = cookieValue;            request.Cookies.Set(hc);        }

上傳方法:

        [HttpPost]        public JsonResult Upload(HttpPostedFileBase fileData)        {            string cookie_LoginUserKey = Request.Form["cookie_LoginUserKey"];            if (realCookie != cookie_LoginUserKey)            {                return Json("上傳失敗");            }            if (fileData != null)            {                try                {                    string CompanyId = ManageProvider.Provider.Current().CompanyId;                    Sys_Company model = companybll.GetEntity(CompanyId);                    string CompanyCode = model.Code;                    string folder = DateTime.Now.ToString("yyyyMM");                    // 檔案上傳後的儲存路徑                    string filePath = Server.MapPath("~/Uploads/" + CompanyCode + "/Web/" + folder + "/");                    if (!Directory.Exists(filePath))                    {                        Directory.CreateDirectory(filePath);                    }                    string fileName = Path.GetFileName(fileData.FileName);// 原始檔案名稱                    string fileExtension = Path.GetExtension(fileName); // 副檔名                    string saveName = Guid.NewGuid().ToString() + fileExtension; // 儲存檔案名稱                    int filesize = fileData.ContentLength / 1024;                    if (filesize > 1024 || filesize <= 2 || (fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".gif"))                    {                        return Json(new { Success = false, Message = "上傳失敗!\r請上傳jpg/png格式圖片,檔案大小不要超過2MB" }, JsonRequestBehavior.AllowGet);                    }                    else                    {                        fileData.SaveAs(filePath + saveName);                        return Json(new { Success = true, FilePath = "/Uploads/"  + CompanyCode + "/Web/" + folder +"/"+ saveName, SaveName = saveName });                    }                }                catch (Exception ex)                {                    return Json(new { Success = false, Message = ex.Message }, JsonRequestBehavior.AllowGet);                }            }            else            {                return Json(new { Success = false, Message = "請選擇要上傳的檔案!" }, JsonRequestBehavior.AllowGet);            }        }

視圖中:

  $(document).ready(function () {        $(‘#file_upload‘).uploadify({            uploader: ‘/School/Sites/Upload‘,            swf: ‘/Content/Scripts/uploadify3.2.1/uploadify.swf‘,            buttonText: "請選擇上傳圖片",            height: 24,            width: 120,            ‘fileExt‘: ‘*.jpg;*.gif,*.png‘,                 //允許上傳的檔案格式為*.jpg,*.gif,*.png            //‘fileDesc‘: ‘Web Image Files(.JPG,.GIF,.PNG)‘,  //過濾掉除了*.jpg,*.gif,*.png的檔案            //‘queueID‘: ‘fileQueue‘,            ‘sizeLimit‘: ‘2048000‘,                         //最大允許的檔案大小為2M            //‘auto‘: false,                                  //需要手動的提交申請            ‘multi‘: false,                                 //一次只允許上傳一張圖片            formData: { @foreach(string k in Request.Cookies.AllKeys)                {                    @:‘[email protected](k)‘ : ‘@Request.Cookies[k].Value‘,                    }                ‘‘: ‘‘            },            ‘onUploadSuccess‘: function (file, data, response) {                var obj = jQuery.parseJSON(data); //把返回的Json序列轉化為obj對象                if (obj.Success) {                    //alert(obj.FilePath);                    $(‘#PictureUrl‘).val(obj.FilePath);                    $(‘#pic‘).attr("src", obj.FilePath);                    $(‘#pic‘).show();                }                else                    alert(obj.Message);            }        });    });

 

MVC中使用jquery uploadify上傳圖片報302錯誤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.