/// <summary> /// 文档页 /// </summary> /// <returns></returns> public Task Archive(ICompatibleHttpContext context) { context.Response.ContentType("text/html;charset=utf-8"); CmsContext ctx = Cms.Context; //检测网站状态及其缓存 if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) { context.Response.ContentType("text/html;charset=utf-8"); var path = context.Request.GetPath(); String archivePath = this.SubPath(path, ctx.SiteAppPath); archivePath = archivePath.Substring(0, archivePath.LastIndexOf(".", StringComparison.Ordinal)); DefaultWebOuput.RenderArchive(ctx, archivePath); } return(SafetyTask.CompletedTask); /* * bool eventResult = false; * if (OnArchiveRequest != null) * { * OnArchiveRequest(ctx, archivePath, ref eventResult); * } * * //如果返回false,则执行默认输出 * if (!eventResult) * { * DefaultWebOuput.RenderArchive(ctx, archivePath); * } */ }
public void Error(int code) { ICompatibleHttpContext ctx = HttpHosting.Context; int statusCode = code; portal.Error(ctx, statusCode); }
/// <summary> /// 首页 /// </summary> public Task Index(ICompatibleHttpContext context) { // 如果启用了静态文件缓存 if (Settings.PERM_INDEX_CACHE_SECOND > 0) { var task = this.CheckStaticIndex(context, Settings.PERM_INDEX_CACHE_SECOND); if (task != null) { return(task); } } var ctx = Cms.Context; SiteDto site = ctx.CurrentSite; // 站点站点路径 if (!this.CheckSiteUrl(context, site)) { return(SafetyTask.CompletedTask); } //检测网站状态及其缓存 if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) { DefaultWebOutput.RenderIndex(ctx); } return(SafetyTask.CompletedTask); }
/// <summary> /// 获取域名路径 /// </summary> /// <param name="context"></param> /// <returns></returns> public static string GetBaseUrl(ICompatibleHttpContext context) { var schema = context.Request.GetProto(); var host = context.Request.GetHost(); return($"{schema}://{host}"); }
/// <summary> /// /// </summary> /// <param name="httpCtx"></param> public CmsContext(ICompatibleHttpContext httpCtx) { _context = httpCtx; if (!Cms.IsInitFinish) { return; } //设置当前站点 var request = _context.Request; var path = request.GetPath(); string appPath = ""; if (path != "/") { appPath = path.Substring(1); if (appPath.EndsWith("/")) { appPath = appPath.Substring(0, appPath.Length - 1); } } CurrentSite = SiteCacheManager.GetSingleOrDefaultSite(request.GetHost(), appPath); //是否为虚拟目录运行 if ((SiteRunType)CurrentSite.RunType == SiteRunType.VirtualDirectory) { _isVirtualDirectoryRunning = true; } this._containCookie = _context.Request.GetHeader("Cookie") != null; }
public CmsContext(ICompatibleHttpContext httpCtx) { _context = httpCtx; if (!Cms.IsInitFinish) { return; } OnBeginRequest?.Invoke(); //设置当前站点 var request = _context.Request; var path = request.GetPath(); string appPath = ""; if (path != "/") { appPath = path.Substring(1); if (appPath.EndsWith("/")) { appPath = appPath.Substring(0, appPath.Length - 1); } } CurrentSite = SiteCacheManager.GetSingleOrDefaultSite(request.GetHost(), appPath); //是否为虚拟目录运行 if ((SiteRunType)CurrentSite.RunType == SiteRunType.VirtualDirectory) { _isVirtualDirectoryRunning = true; } _userDevice = GetUserDeviceSet(_context); }
private DeviceType GetUserDeviceSet(ICompatibleHttpContext ctx) { var s = ctx.Session.GetString("user.device.set"); if (!String.IsNullOrEmpty(s)) { return((DeviceType)Convert.ToInt32(s)); } ctx.Request.TryGetCookie(UserDeviceCookieName, out var ck); if (ck != null) { int.TryParse(ck, out var i); if (Enum.IsDefined(typeof(DeviceType), i)) { SetSessionUserDeviceSet(i); return((DeviceType)i); } } //如果包含手机的域名或agent if (Host.StartsWith("m.") || Host.StartsWith("wap.") || IsMobileAgent()) { return(DeviceType.Mobile); } return(DeviceType.Standard); }
/// <summary> /// 显示错误页面 /// </summary> /// <param name="ctx"></param> /// <param name="statusCode"></param> /// <returns></returns> public Task Error(ICompatibleHttpContext ctx, int statusCode) { if (statusCode == 404) { CmsContext context = Cms.Context; var site = context.CurrentSite; string html; try { var pageName = $"/{site.Tpl}/404"; var tpl = Cms.Template.GetTemplate(pageName); tpl.AddVariable("site", new PageSite(context.CurrentSite)); tpl.AddVariable("page", new PageVariable()); PageUtility.RegisterEventHandlers(tpl); html = tpl.Compile(); } catch { html = "File not found!"; } ctx.Response.ContentType("text/html;charset=utf-8"); ctx.Response.StatusCode(404); ctx.Response.WriteAsync(html); } else { HttpHosting.Context.Response.WriteAsync("internal error"); } return(SafetyTask.CompletedTask); }
/// <summary> /// 检查站点首页路径 /// </summary> /// <param name="ctx"></param> /// <param name="site"></param> /// <returns></returns> private bool CheckSiteUrl(ICompatibleHttpContext ctx, SiteDto site) { // 跳转到自定义地址 if (!string.IsNullOrEmpty(site.Location)) { ctx.Response.Redirect(site.Location, false); //302 return(false); } // 跳转到站点首页 var path = ctx.Request.GetPath(); if (!string.IsNullOrEmpty(site.AppPath) && path == "/") { ctx.Response.Redirect("/" + site.AppPath, false); return(false); } if (string.IsNullOrEmpty(Settings.SYS_SITE_MAP_PATH)) { Settings.SYS_SITE_MAP_PATH = Utils.GetBaseUrl(ctx); Configuration.BeginWrite(); Configuration.UpdateByPrefix("sys"); Configuration.EndWrite(); } if (!Cms.ExistsRobots()) { Cms.GenerateRobots(Utils.GetBaseUrl(ctx)); } return(true); }
private Task CheckStaticIndex(ICompatibleHttpContext context, int seconds) { // 如果非首页访问, 则使用动态的站点首页 var path = context.Request.GetPath(); var appPath = context.Request.GetApplicationPath(); if (path.Length - 1 > appPath.Length) { return(null); } // 缓存失效 var last = Cms.Cache.GetInt(IndexCacheUnixKey); var unix = TimeUtils.Unix(DateTime.Now); if (last > unix - seconds) { var html = Cms.Cache.Get(IndexCacheKey) as string; if (!string.IsNullOrEmpty(html)) { context.Response.ContentType("text/html;charset=utf-8"); return(context.Response.WriteAsync(html)); } } return(null); }
/// <summary> /// 首页 /// </summary> public Task Index(ICompatibleHttpContext context) { // bool eventResult = false; // if (OnIndexRequest != null) // { // OnIndexRequest(base.OutputContext, ref eventResult); // } var ctx = Cms.Context; SiteDto site = ctx.CurrentSite; // 站点站点路径 if (!this.CheckSiteUrl(context, site)) { return(SafetyTask.CompletedTask); } //检测网站状态及其缓存 if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) { DefaultWebOuput.RenderIndex(ctx); } return(SafetyTask.CompletedTask); //如果返回false,则执行默认输出 // if (!eventResult) // { // DefaultWebOuput.RenderIndex(base.OutputContext); // } }
/// <summary> /// </summary> /// <param name="context"></param> /// <returns></returns> public Task ProcessInstallRequest(ICompatibleHttpContext context) { if (context.Request.Method() == "POST") { var rspTxt = Process(context).ToString(); return(context.Response.WriteAsync(rspTxt)); } context.Response.ContentType("text/html;charset=utf-8"); if (File.Exists(Cms.PhysicPath + "/config/install.lock")) { return(context.Response.WriteAsync("系统已经安装成功,如需重新安装请删除:/config/install.lock")); } var fi = new FileInfo(Cms.PhysicPath + "/install/install.html"); if (!fi.Exists) { return(context.Response.WriteAsync("系统丢失文件,无法启动安装向导")); } var bytes = File.ReadAllBytes(fi.FullName); //context.Response.ContentType("text/html;charset=utf-8"); context.Response.WriteAsync(bytes); return(SafetyTask.CompletedTask); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="value"></param> public static void SetCurrentManageSite(ICompatibleHttpContext context, SiteDto value) { var opt = new CookieOptions(); opt.Expires = DateTime.Now.AddDays(2); opt.Path = "/" + Settings.SYS_ADMIN_TAG; context.Response.AppendCookie(CookieNameKey, value.SiteId.ToString(), opt); context.Session.Remove(CurrentSiteSessionStr); }
private Task showError(ICompatibleHttpContext context, string message) { Hashtable hash = new Hashtable { ["error"] = 1, ["message"] = message }; return(context.Response.WriteAsync(JsonAnalyzer.ToJson(hash))); }
/// <summary> /// 栏目页 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task Category(ICompatibleHttpContext context) { context.Response.ContentType("text/html;charset=utf-8"); CmsContext ctx = Cms.Context; //检测网站状态及其缓存 if (ctx.CheckSiteState() && ctx.CheckAndSetClientCache()) { var path = context.Request.GetPath(); var sitePath = ctx.SiteAppPath; // 如果为"/news/",跳转到"/news" var pLen = path.Length; if (path[pLen - 1] == '/') { context.Response.StatusCode(301); context.Response.AddHeader("Location", path.Substring(0, pLen - 1)); return(SafetyTask.CompletedTask); } // 验证是否为当前站点的首页 if (path == sitePath) { return(this.Index(context)); } String catPath = this.SubPath(path, sitePath); int page = 1; //获取页码和tag if (catPath.EndsWith(".html")) { var ls = catPath.LastIndexOf("/", StringComparison.Ordinal); var len = catPath.Length; var begin = ls + 1 + "list_".Length; var ps = catPath.Substring(begin, len - begin - 5); int.TryParse(ps, out page); catPath = catPath.Substring(0, ls); } DefaultWebOutput.RenderCategory(ctx, catPath, page); // //执行 // bool eventResult = false; // if (OnCategoryRequest != null) // { // OnCategoryRequest(ctx, catPath, page, ref eventResult); // } // // //如果返回false,则执行默认输出 // if (!eventResult) // { // DefaultWebOutput.RenderCategory(ctx, catPath, page); // } } return(SafetyTask.CompletedTask); }
private static SiteDto GetSiteFromCookie(ICompatibleHttpContext context, SiteDto site) { if (context.Request.TryGetCookie(CookieNameKey, out var strSiteId)) { var siteId = int.Parse(strSiteId); if (siteId > 0) site = SiteCacheManager.GetSite(siteId); } return site; }
/// <summary> /// 自定义错误页 /// </summary> /// <param name="context"></param> /// <param name="path"></param> /// <returns></returns> public Task Error(HttpContext context) { ICompatibleHttpContext ctx = HttpHosting.Context; int statusCode = 500; if (context.Request.Path.Value.EndsWith("404")) { statusCode = 404; } return(portal.Error(ctx, statusCode)); }
/// <summary> /// 浏览文件 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task KindEditorFileManager(ICompatibleHttpContext context) { string siteId = Logic.CurrentSite.SiteId.ToString(); //根目录路径,相对路径 String rootPath = $"{CmsVariables.RESOURCE_PATH}{siteId}/"; //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/ string appPath = Cms.Context.ApplicationPath; var u = new KindEditor(appPath, rootPath); return(u.FileManagerRequest(Cms.Context.HttpContext)); }
private static Task OutputInternalError(ICompatibleHttpContext context, string className, string methodName, string requestMethod) { var tpl = @" <div style=""font-size:12px;text-align:center;padding:10px;""> <h3>访问的页面出错,代码:502</h3> <strong>这可能因为当前系统版本不支持此功能!</strong><br /> 相关信息:{0}</div> "; context.Response.StatusCode(500); return context.Response.WriteAsync(string.Format(tpl, className + "/" + methodName + "/" + requestMethod)); // OnError("操作未定义!"+className+"/"+methodName); response.End(); }
internal static Task CallMethod(ICompatibleHttpContext context, Type typeName, string methodName) { var requestMethod = context.Request.Method(); var obj = assembly.CreateInstance($"{typeName.FullName}"); if (obj != null) { if (requestMethod != "GET") { methodName += "_" + requestMethod; } var method = obj.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (method != null) { Task task = null; if (method.ReturnType == typeof(Task)) { task = method.Invoke(obj, new object[] { context }) as Task; } else if (method.ReturnType == typeof(string)) { task = context.Response.WriteAsync(method.Invoke(obj, null) as string); } else if (method.ReturnType == typeof(void)) { method.Invoke(obj, null); task = SafetyTask.CompletedTask; } else { var result = method.Invoke(obj, null); task = context.Response.WriteAsync(JsonConvert.SerializeObject(result)); } if (requestMethod == "POST") { CmsCacheUtility.EvalCacheUpdate <MCacheUpdateAttribute>(method); //清理缓存 } return(task); } } return(OutputInternalError(context, typeName.FullName, methodName, requestMethod)); }
/// <summary> /// 检查站点首页路径 /// </summary> /// <param name="ctx"></param> /// <param name="site"></param> /// <param name="siteDto"></param> /// <returns></returns> private bool CheckSiteUrl(ICompatibleHttpContext ctx, SiteDto site) { // 跳转到自定义地址 if (!String.IsNullOrEmpty(site.Location)) { ctx.Response.Redirect(site.Location, false); //302 return(false); } // 跳转到站点首页 var path = ctx.Request.GetPath(); if (!String.IsNullOrEmpty(site.AppPath) && path == "/") { ctx.Response.Redirect("/" + site.AppPath, false); return(false); } return(true); }
private static string GenerateIndexPageCache(ICompatibleHttpContext context, string cacheKey, string cacheUnixKey, int unix) { string html = GenerateCache(cacheKey); // 如果以IP访问,则不保存缓存 String host = context.Request.GetHost(); int i = host.IndexOf(":", StringComparison.Ordinal); if (i != -1) { host = host.Substring(0, i); } String[] hostParts = host.Split('.'); if (!Regex.IsMatch(hostParts[hostParts.Length - 1], "\\d")) { Cms.Cache.Insert(cacheUnixKey, unix); } return(html); }
public Task Change(ICompatibleHttpContext context) { string langOpt = context.Request.Query("lang"); string deviceOpt = context.Request.Query("device"); var isChange = false; int i; if (!string.IsNullOrEmpty(langOpt)) { if (Cms.Context.SetUserLanguage((int)ParseLang(langOpt))) { isChange = true; } } if (!string.IsNullOrEmpty(deviceOpt)) { int.TryParse(deviceOpt, out i); if (Cms.Context.SetUserDevice(i)) { isChange = true; } } if (isChange) { string returnUrl = context.Request.Query("return_url"); if (string.IsNullOrEmpty(returnUrl)) { context.Request.TryGetHeader("UrlReferrer", out var refer); returnUrl = refer.Count == 0 ? "/" : refer.ToString(); } context.Response.StatusCode(302); context.Response.AddHeader("Location", returnUrl); return(SafetyTask.CompletedTask); } return(context.Response.WriteAsync("error params ! should be /" + CmsVariables.DEFAULT_CONTROLLER_NAME + "/change?lang=[1-8]&device=[1-2]")); }
/// <summary> /// 检查位于根目录和root下的静态文件是否存在 /// </summary> /// <param name="context"></param> /// <param name="path"></param> /// <returns></returns> private Task CheckStaticFile(ICompatibleHttpContext context, string path) { if (path.LastIndexOf("/", StringComparison.Ordinal) == 0) { if (!File.Exists(Cms.PhysicPath + path)) { path = "root" + path; if (!File.Exists(Cms.PhysicPath + path)) { return(null); } } // 输出静态文件 var bytes = File.ReadAllBytes(Cms.PhysicPath + path); context.Response.WriteAsync(bytes); return(SafetyTask.CompletedTask); } return(null); }
private Task CheckStaticIndex(ICompatibleHttpContext context, int seconds) { const string cacheKey = "site:page:index:cache"; const string cacheUnixKey = "site:page:index:last-create"; String html; // 如果非首页访问, 则使用动态的站点首页 var req = context.Request; var path = context.Request.GetPath(); var appPath = context.Request.GetApplicationPath(); if (path.Length - 1 > appPath.Length) { return(null); } // 缓存失效 var last = Cms.Cache.GetInt(cacheUnixKey); var unix = TimeUtils.Unix(DateTime.Now); if (last < unix - seconds) { #if DEBUG Console.WriteLine("[ cms][ Info]: update index page cache.."); #endif html = GenerateCache(cacheKey); Cms.Cache.Insert(cacheUnixKey, unix); } else { html = Cms.Cache.Get(cacheKey) as String; if (String.IsNullOrEmpty(html)) { html = GenerateCache(cacheKey); Cms.Cache.Insert(cacheUnixKey, unix); } } context.Response.ContentType("text/html;charset=utf-8"); return(context.Response.WriteAsync(html)); }
/// <summary> /// 首页 /// </summary> public Task Index(ICompatibleHttpContext context) { // 如果启用了静态文件缓存 if (Settings.PERM_INDEX_CACHE_SECOND > 0) { var task = CheckStaticIndex(context, Settings.PERM_INDEX_CACHE_SECOND); if (task != null) { return(task); } } var ctx = Cms.Context; var site = ctx.CurrentSite; // 站点站点路径 if (!CheckSiteUrl(context, site)) { return(SafetyTask.CompletedTask); } //检测网站状态及其缓存 if (ctx.CheckSiteState()) { if (Settings.PERM_INDEX_CACHE_SECOND > 0) { #if DEBUG Console.WriteLine("[ cms][ Info]: update index page cache.."); #endif var unix = TimeUtils.Unix(DateTime.Now); String html = GenerateIndexPageCache(context, IndexCacheKey, IndexCacheUnixKey, unix); context.Response.ContentType("text/html;charset=utf-8"); return(context.Response.WriteAsync(html)); } DefaultWebOutput.RenderIndex(ctx); } return(SafetyTask.CompletedTask); }
public static Task ProcessRequest(ICompatibleHttpContext context) { const string defaultRsp = "jr.Cms WebApi ver 1.0"; var apiName = context.Request.GetParameter("name"); var site = Cms.Context.CurrentSite; string result = null; switch (apiName) { case "rel_link": result = WebApiProcess.GetRelatedlinks( site, context.Request.GetParameter("type") ?? "archive", int.Parse(context.Request.GetParameter("content_id"))); break; case "rel_link_json": result = WebApiProcess.GetRelatedArchiveLinks(site, context.Request.GetParameter("type") ?? "archive", int.Parse(context.Request.GetParameter("content_id"))); break; } return(context.Response.WriteAsync(result ?? defaultRsp)); }
/// <summary> /// 文件浏览 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task FileManagerRequest(ICompatibleHttpContext context) { context.Response.ContentType("application/json; charset=utf-8"); //根目录路径,相对路径 //String rootPath = $"{CmsVariables.RESOURCE_PATH}{siteId}/"; //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/ // string appPath = Cms.Context.ApplicationPath; String rootUrl = $"{(this._appPath == "/" ? "" : this._appPath)}/{this._rootPath}"; //图片扩展名 String fileTypes = "gif,jpg,jpeg,png,bmp"; String currentPath = ""; String currentUrl = ""; String currentDirPath = ""; String moveUpDirPath = ""; String dirPath = EnvUtil.GetBaseDirectory() + this._rootPath; String dirName = context.Request.Query("dir"); if (!String.IsNullOrEmpty(dirName)) { if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1) { return(context.Response.WriteAsync("Invalid Directory name.")); } dirPath += dirName + "/"; rootUrl += dirName + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath).Create(); } } //根据path参数,设置各路径和URL String path = context.Request.Query("path"); path = String.IsNullOrEmpty(path) ? "" : path; if (path == "") { currentPath = dirPath; currentUrl = rootUrl; currentDirPath = ""; moveUpDirPath = ""; } else { currentPath = dirPath + path; currentUrl = rootUrl + path; currentDirPath = path; moveUpDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1"); } //排序形式,name or size or type String order = context.Request.Query("order"); order = String.IsNullOrEmpty(order) ? "" : order.ToLower(); //不允许使用..移动到上一级目录 if (Regex.IsMatch(path, @"\.\.")) { return(context.Response.WriteAsync("Access is not allowed.")); } //最后一个字符不是/ if (path != "" && !path.EndsWith("/")) { return(context.Response.WriteAsync("Parameter is not valid.")); } //目录不存在或不是目录 if (!Directory.Exists(currentPath)) { return(context.Response.WriteAsync("Directory does not exist.")); } //遍历目录取得文件信息 string[] dirList = Directory.GetDirectories(currentPath); string[] fileList = Directory.GetFiles(currentPath); switch (order) { case "size": Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new SizeSorter()); break; case "type": Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new TypeSorter()); break; case "name": default: Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new NameSorter()); break; } Hashtable result = new Hashtable(); result["moveup_dir_path"] = moveUpDirPath; result["current_dir_path"] = currentDirPath; result["current_url"] = currentUrl; result["total_count"] = dirList.Length + fileList.Length; List <Hashtable> dirFileList = new List <Hashtable>(); for (int i = 0; i < dirList.Length; i++) { DirectoryInfo dir = new DirectoryInfo(dirList[i]); Hashtable hash = new Hashtable { ["is_dir"] = true, ["has_file"] = (dir.GetFileSystemInfos().Length > 0), ["filesize"] = 0, ["is_photo"] = false, ["filetype"] = "", ["filename"] = dir.Name, ["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") }; dirFileList.Add(hash); } for (int i = 0; i < fileList.Length; i++) { FileInfo file = new FileInfo(fileList[i]); if (file.Extension.Equals("")) { continue; } Hashtable hash = new Hashtable { ["is_dir"] = false, ["has_file"] = false, ["filesize"] = file.Length, ["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0), ["filetype"] = file.Extension.Substring(1), ["filename"] = file.Name, ["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss") }; dirFileList.Add(hash); } string files = String.Empty; int j = 0; foreach (Hashtable h in dirFileList) { files += JsonAnalyzer.ToJson(h); if (++j < dirFileList.Count) { files += ","; } } result["file_list"] = "[" + files + "]"; context.Response.ContentType("application/json; charset=utf-8"); return(context.Response.WriteAsync(JsonAnalyzer.ToJson(result))); }
/// <summary> /// 处理上传 /// </summary> /// <param name="context"></param> /// <returns></returns> public Task UploadRequest(ICompatibleHttpContext context) { context.Response.ContentType("application/json; charset=utf-8"); var path = context.Request.GetPath(); //String aspxUrl = path.Substring(0, path.LastIndexOf("/") + 1); String saveUrl = $"{(this._appPath == "/" ? "" : this._appPath)}/{this._rootPath}"; //定义允许上传的文件扩展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp,webp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,7z"); //最大文件大小 int maxSize = 10240000; ICompatiblePostedFile imgFile = context.Request.File("imgFile"); if (imgFile == null) { return(this.showError(context, "请选择文件。")); } String dirPath = EnvUtil.GetBaseDirectory() + this._rootPath; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath).Create(); //return showError(context,"上传目录不存在。"); } String dirName = context.Request.Query("dir"); if (String.IsNullOrEmpty(dirName)) { dirName = "image"; } if (!extTable.ContainsKey(dirName)) { return(this.showError(context, "目录名不正确。")); } String fileName = imgFile.GetFileName(); String fileExt = Path.GetExtension(fileName).ToLower(); if (imgFile.GetLength() > maxSize) { return(this.showError(context, "上传文件大小超过限制。")); } if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) { return(this.showError(context, "上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。")); } //创建文件夹 dirPath += dirName + "/"; saveUrl += dirName + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath).Create(); } String ymd = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo); dirPath += ymd + "/"; saveUrl += ymd + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String originName = UploadUtils.GetUploadFileName(imgFile); String newFileName = originName + fileExt; //String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt; // 自动将重复的名称命名 String targetPath = dirPath + newFileName; int i = 0; while (File.Exists(targetPath)) { i++; newFileName = $"{originName}_{i.ToString()}{fileExt}"; targetPath = dirPath + newFileName; } SaveFile(imgFile, targetPath); String fileUrl = saveUrl + newFileName; Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fileUrl; return(context.Response.WriteAsync(JsonAnalyzer.ToJson(hash))); }
protected CmsTemplateDataMethod(ICompatibleHttpContext context) : base(context) { }