public ActionResult UploadHead(HttpPostedFileBase head) //命名和上传控件name 一样 { BaseState state = null; try { if ((head == null)) { state = (new BaseState(-1, "无上传文件")); } else { var supportedTypes = new[] {"jpg", "jpeg", "png", "gif", "bmp"}; var fileExt = Path.GetExtension(head.FileName).Substring(1); if (!supportedTypes.Contains(fileExt)) { state = (new BaseState(-1, "文件类型不正确")); } else if (head.ContentLength > 1024*1000*10) { state = (new BaseState(-2, "文件太大")); } else { var r = new Random(); var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + r.Next(10000) + "." + fileExt; var filepath = Path.Combine(this.Server.MapPath("~/avatarImage/temp"), filename); head.SaveAs(filepath); var serverfile = HttpServerInfo.BaseUrl + "/avatarImage/temp/" + filename; state = new BaseState(0, serverfile); } } var jsonstr = JsonConvert.ToJsonStr(state); var script = string.Format( "<script type='text/javascript'> if( top.fileuploadcallback ){{ top.fileuploadcallback({0});}}else{{window.alert('不在的图片回调方法');}}</script>", jsonstr); return this.Content(script); } catch (Exception) { throw; return this.Json(new {msg = -3}); } }
private static string ModifiyScript(BaseState state) { var jsonstr = JsonConvert.ToJsonStr(state); var script = string.Format( "<script type='text/javascript'> if( top.fileupladmodifycallback ){{ top.fileupladmodifycallback({0});}}else{{window.alert('不在的图片回调方法');}}</script>", jsonstr); return script; }
//[ValidateAntiForgeryToken] public ActionResult SaveHead(int x, int y, int width, int height, string headFileName) { if (!WebSecurity.IsAuthenticated) { return this.Content(ModifiyScript(new BaseState(-1, "用户还未登录"))); } var model = new UploadImageModel(); model.headFileName = this.Request["headFileName"]; model.x = Convert.ToInt32(this.Request["x"]); model.y = Convert.ToInt32(this.Request["y"]); model.width = Convert.ToInt32(this.Request["width"]); model.height = Convert.ToInt32(this.Request["height"]); var filepath = Path.Combine(this.Server.MapPath("~/avatarImage/temp"), model.headFileName); var fileExt = Path.GetExtension(filepath); var key = ""; using (var cutedstream = this.CutAvatar(filepath, model.x, model.y, model.width, model.height, 75L, 180) ) { key = this._imagefile.SaveImageFile(cutedstream, model.headFileName, new[] { new ImagesSize { Height = 180, Width = 180 }, new ImagesSize { Height = 75, Width = 75 }, new ImagesSize { Height = 50, Width = 50 }, new ImagesSize { Height = 25, Width = 25 }, }); cutedstream.Close(); } this._userService.UpdateUserAvatar(WebSecurity.CurrentUserId, key); //Dev.Comm.FileUtil.DeleteFile(filepath); var state = new BaseState(0, key); var script = ModifiyScript(state); return this.Content(script); return this.Json(new BaseState(0, key), JsonRequestBehavior.AllowGet); }