コード例 #1
0
        public JsonResult UploadAvatar()
        {
            ResultModel <string> model = new ResultModel <string>();

            if (base.IsLogin.IsFalse())
            {
                model.ResultInfo = "您还没有登录!";
                return(Json(model, JsonRequestBehavior.AllowGet));
            }
            try
            {
                _service.Command <UserCenterOutsourcing>((db, o) =>
                {
                    var imgObj = new UploadImage();
                    var file   = Request.Files[0];
                    if (file.ContentLength / 1024.0 / 1024.0 > 1)
                    {
                        model.ResultInfo = "上传图片不能超过一M!";
                    }
                    else if (file.ContentType.IsIn("image/png", "image/gif", "image/jpg", "image/jpeg").IsFalse())
                    {
                        model.ResultInfo = "上传失败,您的图片不是PNG GIF JPG 格式!";
                    }
                    else
                    {
                        model.IsSuccess  = true;
                        string webPath   = "/_theme/img/avatar" + _userInfo.Id + ".jpg";
                        string savePath  = FileSugar.GetMapPath("~" + webPath);
                        string smallPath = FileSugar.GetMapPath("~/_theme/img/_avatar" + _userInfo.Id + ".jpg");
                        file.SaveAs(savePath);
                        model.ResultInfo = Url.Content("~/" + webPath) + "?r=" + Guid.NewGuid();
                        imgObj.CreateSmallPhoto(savePath, 100, 100, smallPath);//生成缩略图
                        FileSugar.DeleteFile(savePath);
                        FileSugar.Move(smallPath, savePath);
                        db.Update <UserInfo>(new { avatar = webPath + "?r=" + RandomSugar.GetRandomNum(5) }, it => it.Id == _userInfo.Id);
                        RestCurrentUserCache();
                    }
                });
                return(Json(model));
            }
            catch (Exception ex)
            {
                PubMethod.WirteExp(ex);
                model.ResultInfo = "上传失败!";
            }
            return(Json(model, JsonRequestBehavior.AllowGet));
        }