zoukankan      html  css  js  c++  java
  • KindEditor编辑器在ASP.NET中的使用

    KindEditor编辑器在ASP.NET中的使用

    最近做的项目中都有用到富文本编辑器,一直在寻找最后用的富文本编辑器,之前用过CKEditor,也用过UEditor,这次打算用 一下KindEditor。

    KindEditor简介

    KindEditor是一套开源的HTML可视化编辑器,主要用于让用户在网站上获得所见即所得编辑效果,兼容IE、Firefox、Chrome、Safari、Opera等主流浏览器。KindEditor使用JavaScript编写,可以无缝的于Java、.NET、PHP、ASP等程序接合。 KindEditor非常适合在CMS、商城、论坛、博客、Wiki、电子邮件等互联网应用上使用,2006年7月首次发布2.0以来,KindEditor依靠出色的用户体验和领先的技术不断扩大编辑器市场占有率,目前在国内已经成为最受欢迎的编辑器之一。[来自百度百科]

    官网简介官网下载官方文档官网Demo演示

    KindEditor使用

    1. 将开发包导入到项目

      将下载的开发包中不需要的删掉,只保留项目需要的文件,我的项目是ASP.NET项目,所引用的开发包资源如下图所示

    2. 在页面中添加引用

    3. 页面初始化

      html设置:

      js初始化:

    4. 获取和设置编辑器的值

      获取编辑器的值:

      1. 直接通过editor获取

      var html = editor.html();

      1. 先把数据同步到textarea中,再获取textarea的值

        editor.sync();

        //原生js获取

        var html = document.getElementById("editor").value;

        //jquery获取

        var html =$("#editor").val();

        //KindEditor 方式

        var html = K('#editor').val();

        设置编辑器的值:

            editor.html('html内容');

    上传文件处理程序

    参考所给的示例,只是对示例加以验证,验证是否有上传权限

    上传文件列表处理程序

    获取上传文件列表同样的,首先进行权限验证:

      1 public class UploadFileHandler : IHttpHandler, IRequiresSessionState
      2     {
      3         private static HttpResponse Response = null;
      4         //最大文件大小
      5         const int MAXFILESIZE = 10240*1024;
      6 
      7         public void ProcessRequest(HttpContext context)
      8         {
      9             //验证上传权限
     10             if (context.Session["User"] == null)
     11             {
     12                 context.Response.Write("no permission");
     13                 context.Response.End();
     14                 return;
     15             }
     16             Response = context.Response;
     17             string flag = context.Request["customUpload"];
     18             //从配置文件中获取网站首页路径
     19             String aspxUrl = Common.ConfigurationHelper.AppSetting("HomeUrlInfo");
     20             //文件保存目录路径
     21             System.Text.StringBuilder savePath = new System.Text.StringBuilder("/Upload/");
     22             try
     23             {
     24                 //定义允许上传的文件扩展名
     25                 Hashtable extTable = new Hashtable();
     26                 extTable.Add("image", "jpg,jpeg,png,bmp");
     27                 extTable.Add("flash", "swf,flv");
     28                 extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
     29                 extTable.Add("file", "doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar");
     30                 //获取上传文件
     31                 HttpPostedFile imgFile = context.Request.Files["imgFile"];
     32                 if (imgFile == null)
     33                 {
     34                     imgFile = context.Request.Files["Filedata"];
     35                 }
     36                 //当前时间字符串
     37                 string timeString = DateTime.Now.ToString("yyyyMMddHHmmssfff");
     38                 //设置存储目录
     39                 String dirName = context.Request.QueryString["dir"];
     40                 if (String.IsNullOrEmpty(dirName))
     41                 {
     42                     dirName = "image";
     43                 }
     44                 if (!extTable.ContainsKey(dirName))
     45                 {
     46                     showError("目录名不正确");
     47                 }
     48                 if (imgFile.InputStream == null || imgFile.InputStream.Length > MAXFILESIZE)
     49                 {
     50                     showError("上传文件大小超过限制");
     51                 }
     52                 //获取文件扩展名
     53                 string fileExt = Path.GetExtension(imgFile.FileName).ToLower();
     54                 if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
     55                 {
     56                     showError("上传文件扩展名是不允许的扩展名。
    只允许" + ((String)extTable[dirName]) + "格式。");
     57                 }
     58                 //创建文件夹
     59                 savePath.Append(dirName + "/");
     60                 string serverPath = Common.PathHelper.MapPath(savePath.ToString());
     61                 if (!Directory.Exists(serverPath))
     62                 {
     63                     Directory.CreateDirectory(serverPath);
     64                 }
     65                 String newFileName = timeString + fileExt;
     66                 String filePath = serverPath + newFileName;
     67                 //保存到服务器端
     68                 imgFile.SaveAs(filePath);
     69                 savePath.Append(newFileName);
     70                 //文件相对网站的虚拟路径
     71                 String fileUrl = savePath.ToString();
     72                 if (String.IsNullOrEmpty(flag))
     73                 {
     74                     fileUrl = aspxUrl + savePath.ToString();
     75                 }
     76                 Hashtable hash = new Hashtable();
     77                 hash["error"] = 0;
     78                 hash["url"] = fileUrl;
     79                 context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
     80                 context.Response.Write(Common.ConverterHelper.ObjectToJson(hash));
     81                 context.Response.End();
     82 
     83             }
     84             catch (System.Threading.ThreadAbortException)
     85             {
     86 
     87             }
     88             catch (HttpException ex)
     89             {
     90                 //context.Response.Write("Error");
     91                 //记录日志
     92                 new Common.LogHelper(typeof(UploadFileHandler)).Error(ex);
     93             }
     94             catch (Exception ex)
     95             {
     96                 //context.Response.Write("Error");
     97                 //记录日志
     98                 new Common.LogHelper(typeof(UploadFileHandler)).Error(ex);
     99             }
    100         }
    101 
    102 
    103         private void showError(string message)
    104         {
    105             Hashtable hash = new Hashtable();
    106             hash["error"] = 1;
    107             hash["message"] = message;
    108             Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
    109             Response.Write(Common.ConverterHelper.ObjectToJson(hash));
    110             Response.End();
    111         }
    UploadFileHandler Code
      1 using System;
      2 using System.Collections;
      3 using System.Collections.Generic;
      4 using System.IO;
      5 using System.Text.RegularExpressions;
      6 using System.Web;
      7 using System.Web.SessionState;
      8 
      9 namespace WebApplication1.Admin
     10 {
     11     public class FileManagerHandler : IHttpHandler,IRequiresSessionState
     12     {
     13         public void ProcessRequest(HttpContext context)
     14         {
     15             //验证权限
     16             if (context.Session["User"] == null)
     17             {
     18                 context.Response.Write("no permission");
     19                 context.Response.End();
     20                 return;
     21             }
     22             //从配置文件中读取网址信息
     23             String aspxUrl = Common.ConfigurationHelper.AppSetting("HomeUrlInfo");
     24             //根目录路径,相对路径
     25             String rootPath = "/Upload/";
     26             //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
     27             String rootUrl = aspxUrl + "Upload/";
     28             //图片扩展名
     29             String fileTypes = "jpg,jpeg,png,bmp";
     30             String currentPath = "";
     31             String currentUrl = "";
     32             String currentDirPath = "";
     33             String moveupDirPath = "";
     34             try
     35             {
     36                 String dirPath = context.Server.MapPath(rootPath);
     37                 String dirName = context.Request.QueryString["dir"];
     38                 if (!String.IsNullOrEmpty(dirName))
     39                 {
     40                     if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1)
     41                     {
     42                         context.Response.Write("Invalid Directory name.");
     43                         context.Response.End();
     44                     }
     45                     dirPath += dirName + "/";
     46                     rootUrl += dirName + "/";
     47                     if (!Directory.Exists(dirPath))
     48                     {
     49                         Directory.CreateDirectory(dirPath);
     50                     }
     51                 }
     52 
     53                 //根据path参数,设置各路径和URL
     54                 String path = context.Request.QueryString["path"];
     55                 path = String.IsNullOrEmpty(path) ? "" : path;
     56                 if (path == "")
     57                 {
     58                     currentPath = dirPath;
     59                     currentUrl = rootUrl;
     60                     currentDirPath = "";
     61                     moveupDirPath = "";
     62                 }
     63                 else
     64                 {
     65                     currentPath = dirPath + path;
     66                     currentUrl = rootUrl + path;
     67                     currentDirPath = path;
     68                     moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^/]+/$", "$1");
     69                 }
     70 
     71                 //排序形式,name or size or type
     72                 String order = context.Request.QueryString["order"];
     73                 order = String.IsNullOrEmpty(order) ? "" : order.ToLower();
     74 
     75                 //不允许使用..移动到上一级目录
     76                 if (Regex.IsMatch(path, @".."))
     77                 {
     78                     context.Response.Write("Access is not allowed.");
     79                     context.Response.End();
     80                 }
     81                 //最后一个字符不是/
     82                 if (path != "" && !path.EndsWith("/"))
     83                 {
     84                     context.Response.Write("Parameter is not valid.");
     85                     context.Response.End();
     86                 }
     87                 //目录不存在或不是目录
     88                 if (!Directory.Exists(currentPath))
     89                 {
     90                     context.Response.Write("Directory does not exist.");
     91                     context.Response.End();
     92                 }
     93 
     94                 //遍历目录取得文件信息
     95                 string[] dirList = Directory.GetDirectories(currentPath);
     96                 string[] fileList = Directory.GetFiles(currentPath);
     97                 //排序方式
     98                 switch (order)
     99                 {
    100                     case "size":
    101                         Array.Sort(dirList, new NameSorter());
    102                         Array.Sort(fileList, new SizeSorter());
    103                         break;
    104                     case "type":
    105                         Array.Sort(dirList, new NameSorter());
    106                         Array.Sort(fileList, new TypeSorter());
    107                         break;
    108                     case "name":
    109                     default:
    110                         Array.Sort(dirList, new NameSorter());
    111                         Array.Sort(fileList, new NameSorter());
    112                         break;
    113                 }
    114                 Hashtable result = new Hashtable();
    115                 result["moveup_dir_path"] = moveupDirPath;
    116                 result["current_dir_path"] = currentDirPath;
    117                 result["current_url"] = currentUrl;
    118                 result["total_count"] = dirList.Length + fileList.Length;
    119                 List<Hashtable> dirFileList = new List<Hashtable>();
    120                 result["file_list"] = dirFileList;
    121                 for (int i = 0; i < dirList.Length; i++)
    122                 {
    123                     DirectoryInfo dir = new DirectoryInfo(dirList[i]);
    124                     Hashtable hash = new Hashtable();
    125                     hash["is_dir"] = true;
    126                     hash["has_file"] = (dir.GetFileSystemInfos().Length > 0);
    127                     hash["filesize"] = 0;
    128                     hash["is_photo"] = false;
    129                     hash["filetype"] = "";
    130                     hash["filename"] = dir.Name;
    131                     hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
    132                     dirFileList.Add(hash);
    133                 }
    134                 for (int i = 0; i < fileList.Length; i++)
    135                 {
    136                     FileInfo file = new FileInfo(fileList[i]);
    137                     Hashtable hash = new Hashtable();
    138                     hash["is_dir"] = false;
    139                     hash["has_file"] = false;
    140                     hash["filesize"] = file.Length;
    141                     hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0);
    142                     hash["filetype"] = file.Extension.Substring(1);
    143                     hash["filename"] = file.Name;
    144                     hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss");
    145                     dirFileList.Add(hash);
    146                 }
    147                 context.Response.AddHeader("Content-Type", "application/json; charset=UTF-8");
    148                 context.Response.Write(Common.ConverterHelper.ObjectToJson(result));
    149                 context.Response.End();
    150             }
    151             catch (IOException ex)
    152             {
    153                 context.Response.Write("Error");
    154                 //记录日志
    155                 new Common.LogHelper(typeof(FileManagerHandler)).Error(ex);
    156             }
    157             catch (SystemException ex)
    158             {
    159                 context.Response.Write("Error");
    160                 //记录日志
    161                 new Common.LogHelper(typeof(FileManagerHandler)).Error(ex);
    162             }
    163             catch (Exception ex)
    164             {
    165                 context.Response.Write("Error");
    166                 //记录日志
    167                 new Common.LogHelper(typeof(FileManagerHandler)).Error(ex);
    168             }
    169         }
    170 
    171         public bool IsReusable
    172         {
    173             get
    174             {
    175                 return true;
    176             }
    177         }
    178 
    179     }
    180 
    181     class NameSorter : IComparer
    182     {
    183         public int Compare(object x, object y)
    184         {
    185             if (x == null && y == null)
    186             {
    187                 return 0;
    188             }
    189             if (x == null)
    190             {
    191                 return -1;
    192             }
    193             if (y == null)
    194             {
    195                 return 1;
    196             }
    197             FileInfo xInfo = new FileInfo(x.ToString());
    198             FileInfo yInfo = new FileInfo(y.ToString());
    199 
    200             return xInfo.FullName.CompareTo(yInfo.FullName);
    201         }
    202     }
    203     
    204     class SizeSorter : IComparer
    205     {
    206         public int Compare(object x, object y)
    207         {
    208             if (x == null && y == null)
    209             {
    210                 return 0;
    211             }
    212             if (x == null)
    213             {
    214                 return -1;
    215             }
    216             if (y == null)
    217             {
    218                 return 1;
    219             }
    220             FileInfo xInfo = new FileInfo(x.ToString());
    221             FileInfo yInfo = new FileInfo(y.ToString());
    222 
    223             return xInfo.Length.CompareTo(yInfo.Length);
    224         }
    225     }
    226     
    227     class TypeSorter : IComparer
    228     {
    229         public int Compare(object x, object y)
    230         {
    231             if (x == null && y == null)
    232             {
    233                 return 0;
    234             }
    235             if (x == null)
    236             {
    237                 return -1;
    238             }
    239             if (y == null)
    240             {
    241                 return 1;
    242             }
    243             FileInfo xInfo = new FileInfo(x.ToString());
    244             FileInfo yInfo = new FileInfo(y.ToString());
    245 
    246             return xInfo.Extension.CompareTo(yInfo.Extension);
    247         }
    248     }
    249 }
    FileManagerHandler Code
  • 相关阅读:
    Java 基础(六):循环
    Java基础(五):数组
    Java 基础(四):从面试题看String
    Java Grammar(二):运算符
    「每日五分钟,玩转JVM」:指针压缩
    一份让你效率翻倍的年终总结
    「每日五分钟,玩转 JVM」:GC 概览
    「每日五分钟,玩转JVM」:对象内存布局
    「每日五分钟,玩转JVM」:对象从哪来
    Azure Web App (二)使用部署槽切换部署环境代码
  • 原文地址:https://www.cnblogs.com/weihanli/p/kindEditorDemoInASPDotNet.html
Copyright © 2011-2022 走看看