0

我不知道为什么我的身份验证 cookie 会消失。我将 Valums Ajax Upload 与其他几个 ajax 请求结合使用来构建用户的头像。cookie 何时消失是非常随机的。我可以毫无问题地上传 4 个文件,然后可能会上传 2 个文件(再次登录后)。似乎在我调用 CreateAvatar 方法之后,这可能会出现问题,但就像我说的那样,它不会一直发生。我错过了什么?

JavaScript:

$(function () {
        //This is the Upload Method
        var fileCount = 0;
        var uploader = new qq.FileUploader({
            element: document.getElementById('file-uploader'),
            action: '/Admin/Avatar/AvatarUpload',
            debug: true,
            params: {
                'userId': '@ViewBag.UserId'
            },
            onSubmit: function (id, fileName) {
                fileCount++;
            },
            onComplete: function (id, fileName, responseJson) {
                if (responseJson.success) {
                    //fileCount--;
                                        if (createAvatar(responseJson.file, responseJson.imageId)) {
                                            fileCount--;

                                        } else {
                                            fileCount--;
                                            //alert('There was an error when trying to save ' + fileName);
                                        }
                } else {
                    $("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
                    fileCount--;
                }

                if (fileCount == 0) {

                }

            },
            onCancel: function (id, fileName) {
                fileCount--;
                if (fileCount == 0) {
                    parent.$.fn.colorbox.close();
                }
            }
        });
    });

    //This Creates the Avatar Object
    function createAvatar(fileName, imageId) {

        var avatarUploadModel = { 
            UploadFileName: fileName,
            UserId: '@ViewBag.UserId',
            ImageId: imageId

        };
        $.ajax({
            url: '/Admin/Avatar/CreateAvatar/',
            type: 'POST',
            cache: false,
            timeout: 100000,
            data: JSON.stringify(avatarUploadModel),
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            error: function (xhr, status, error) {
                alert(error + " " + status);
            },
            success: function (data) {
                if (data.success) {

                    loadAvatar(data.avatarModel);
                    return true;
                } else {
                    return false;
                }
            }

        });
    }

    //This loads the partial to view the avatar after upload
    function loadAvatar(avatarModel) {

        $.ajax({
            url: '/Admin/Avatar/AvatarEdit',
            type: 'GET',
            cache: false,
            timeout: 100000,
            data: avatarModel,
            dataType: "html",
            error: function (xhr, status, error) {
                alert(error + " " + status);
            },
            success: function (data) {

                $("#avatarOriginal").html(data);

            }

        });
    }

登录方式:

var user = _userService.GetByUserName(model.Username);
                var authTicket = new
                    FormsAuthenticationTicket(1, //version
                                              user.Id.ToString(), // user name
                                              DateTime.Now,
                                              DateTime.Now.AddMinutes(40), //Expiration
                                              model.RememberMe, //Persistent,
                                              user.Username);

                var encTicket = FormsAuthentication.Encrypt(authTicket);
                HttpContext.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));


                return Json(new {success = true, url = model.ReturnUrl}, JsonRequestBehavior.AllowGet);

控制器上的上传方法:

[HttpPost]
        public ActionResult AvatarUpload(HttpPostedFileBase fileData)
        {
            var id = Guid.NewGuid();
            string fileName;
            var serverPath = Server.MapPath("~/Areas/Admin/TemporaryUploads/");
            if (fileData != null)
            {
                var fileRenamed = System.IO.Path.GetFileName(id + "_" + fileData.FileName);
                fileName = Server.MapPath("~/Areas/Admin/TemporaryUploads/" + fileRenamed);
                fileData.SaveAs(fileName);
            }
            else
            {
                var ajaxUploadFileData = Request["qqfile"];
                fileName = Path.Combine(serverPath, id + "_" + Path.GetFileName(ajaxUploadFileData));
                using (var output = System.IO.File.Create(fileName))
                {
                    Request.InputStream.CopyTo(output);
                }
            }


            return Json(new {success = true, file = fileName, imageId = id}, JsonRequestBehavior.AllowGet);
        }

创建头像方法:

[HttpPost]
        public ActionResult CreateAvatar(AvatarModel avatarModel)
        {

            try
            {

                var image = new WebImage(avatarModel.UploadFileName).Resize(400, 400, true);
                var imageFileName = Path.GetFileName(avatarModel.UploadFileName);
                var avatar = new Domain.YogaDiVitaContext.Model.Avatar()
                                 {
                                     CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
                                     ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
                                     UserId = avatarModel.UserId,
                                     Image = new Image()
                                                 {
                                                     CreatedById = Guid.Parse(HttpContext.User.Identity.Name),
                                                     ModifiedById = Guid.Parse(HttpContext.User.Identity.Name),
                                                     OriginalImageRelativePath = "original/" + imageFileName
                                                 }
                                 };

                var user = UserService.FindById(avatarModel.UserId);
                if (user.Avatar != null)
                    RemoveAvatar(user.Avatar);

                avatar = _avatarService.Create(avatar);

                user.Avatar = avatar;
                UserService.Update(user);

                var basePath = Server.MapPath("~/" + avatar.ToAvatarBasePath(GlobalVariables.AvatarPath));
                Directory.CreateDirectory(basePath);
                Directory.CreateDirectory(basePath + "/thumbnail");
                Directory.CreateDirectory(basePath + "/fullsize");
                Directory.CreateDirectory(basePath + "/original");
                image.Save(Server.MapPath("~/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath)));

                avatarModel.Width = image.Width;
                avatarModel.Height = image.Height;
                avatarModel.Top = image.Height*0.1;
                avatarModel.Left = image.Width*0.9;
                avatarModel.Right = image.Width*0.9;
                avatarModel.Bottom = image.Height*0.9;
                avatarModel.OriginalImagePath = "/" + avatar.ToAvatarOriginalPath(GlobalVariables.AvatarPath);


                System.IO.File.Delete(avatarModel.UploadFileName);

                return Json(new {success = true, avatarModel}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception exception)
            {
                return Json(new {message = exception.Message}, JsonRequestBehavior.AllowGet);
            }
        }

加载头像部分:

public ActionResult AvatarEdit(AvatarModel avatarModel)
        {
            return PartialView("AvatarCropPartial", avatarModel);
        }
4

0 回答 0