当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET配置KindEditor文本编辑器图文教程

ASP.NET配置KindEditor文本编辑器图文教程

2017年12月12日  | 移动技术网IT编程  | 我要评论

1.什么是kindeditor

kindeditor 是一套开源的在线html编辑器,主要用于让用户在网站上获得所见即所得编辑效果,开发人员可以用 kindeditor 把传统的多行文本输入框(textarea)替换为可视化的富文本输入框。 kindeditor 使用 javascript 编写,可以无缝地与 java、.net、php、asp 等程序集成,比较适合在 cms、商城、论坛、博客、wiki、电子邮件等互联网应用上使用。

2.前期准备

到官网下载最新版的,解压文件后可得

文件结构:

asp:与asp结合的示例代码

asp.net:与asp.net结合的示例代码

attached:上传文件的根目录,可在相关的代码中修改

examples:功能演示的示例代码

jsp:与jsp结合的示例代码

lang:语言包

php:与php结合的示例代码

plugins:控件的功能代码的实现

kindeditor.js:配置文件

kindeditor-min.js:集成文件

由于使用的是asp.net,所以将不需要的文件夹删掉。其中在asp.net中demo.aspx是参考代码,也可以删掉。

 3.配置kindeditor

(1)新建网站,将精简后的kindeditor文件夹放到网站根目录下下,并且引用kindeditor/asp.net/bin/litjson.dll文件。

(2)新建index.aspx文件,引入相关文件

 <link href="kindeditor/plugins/code/prettify.css" rel="stylesheet" type="text/css" />
 <script src="kindeditor/lang/zh_cn.js" type="text/javascript"></script>
 <script src="kindeditor/kindeditor.js" type="text/javascript"></script>
 <script src="kindeditor/plugins/code/prettify.js" type="text/javascript"></script> 
 <script type="text/javascript">
 kindeditor.ready(function (k) {
  var editor = k.create('#content', {
  //上传管理
  uploadjson: 'kindeditor/asp.net/upload_json.ashx',
  //文件管理
  filemanagerjson: 'kindeditor/asp.net/file_manager_json.ashx',
  allowfilemanager: true,
  //设置编辑器创建后执行的回调函数
  aftercreate: function () {
   var self = this;
   k.ctrl(document, 13, function () {
   self.sync();
   k('form[name=example]')[0].submit();
   });
   k.ctrl(self.edit.doc, 13, function () {
   self.sync();
   k('form[name=example]')[0].submit();
   });
  },
  //上传文件后执行的回调函数,获取上传图片的路径
  afterupload : function(url) {
   alert(url);
  },
  //编辑器高度
  width: '700px',
  //编辑器宽度
  height: '450px;',
  //配置编辑器的工具栏
  items: [
  'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
  'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
  'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
  'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
  'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
  'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  'anchor', 'link', 'unlink', '|', 'about'
  ]
  });
  prettyprint();
 });
 </script>

(3)在页面中添加一个textbox控件,将id命名为content,把属性"textmode"属性改为multiline

<body>
 <form id="form1" runat="server">
 <div id="main">
 <asp:textbox id="content" name="content" textmode="multiline" runat="server"></asp:textbox>
 </div>
 </form>
</body>

 (4)在浏览器查看

4.附件上传原理

在asp.net文件夹下有两个重要的file_manager_json.ashx,upload_json.ashx,一个负责文件管理,一个负责上传管理。你可以根据自己需求进行相关修改。

原理:通过实现接口ihttphandler来接管http请求。

file_manager_json.ashx

<%@ webhandler language="c#" class="filemanager" %>

/**
 * kindeditor asp.net
 * 文件管理
 */

using system;
using system.collections;
using system.web;
using system.io;
using system.text.regularexpressions;
using litjson;
using system.collections.generic;

public class filemanager : ihttphandler
{
 public void processrequest(httpcontext context)
 {
 string aspxurl = context.request.path.substring(0, context.request.path.lastindexof("/") + 1);

 
 //根目录路径,相对路径
 string rootpath = "http://www.cnblogs.com/attached/";
 //根目录url,可以指定绝对路径,比如 http://www.yoursite.com/attached/
 string rooturl = aspxurl + "http://www.cnblogs.com/attached/";
 //图片扩展名
 string filetypes = "gif,jpg,jpeg,png,bmp";

 string currentpath = "";
 string currenturl = "";
 string currentdirpath = "";
 string moveupdirpath = "";

 string dirpath = context.server.mappath(rootpath);
 string dirname = context.request.querystring["dir"];
 if (!string.isnullorempty(dirname)) {
  if (array.indexof("image,flash,media,file".split(','), dirname) == -1) {
  context.response.write("invalid directory name.");
  context.response.end();
  }
  dirpath += dirname + "/";
  rooturl += dirname + "/";
  if (!directory.exists(dirpath)) {
  directory.createdirectory(dirpath);
  }
 }

 //根据path参数,设置各路径和url
 string path = context.request.querystring["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.querystring["order"];
 order = string.isnullorempty(order) ? "" : order.tolower();

 //不允许使用..移动到上一级目录
 if (regex.ismatch(path, @"\.\."))
 {
  context.response.write("access is not allowed.");
  context.response.end();
 }
 //最后一个字符不是/
 if (path != "" && !path.endswith("/"))
 {
  context.response.write("parameter is not valid.");
  context.response.end();
 }
 //目录不存在或不是目录
 if (!directory.exists(currentpath))
 {
  context.response.write("directory does not exist.");
  context.response.end();
 }

 //遍历目录取得文件信息
 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>();
 result["file_list"] = dirfilelist;
 for (int i = 0; i < dirlist.length; i++)
 {
  directoryinfo dir = new directoryinfo(dirlist[i]);
  hashtable hash = new hashtable();
  hash["is_dir"] = true;
  hash["has_file"] = (dir.getfilesysteminfos().length > 0);
  hash["filesize"] = 0;
  hash["is_photo"] = false;
  hash["filetype"] = "";
  hash["filename"] = dir.name;
  hash["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]);
  hashtable hash = new hashtable();
  hash["is_dir"] = false;
  hash["has_file"] = false;
  hash["filesize"] = file.length;
  hash["is_photo"] = (array.indexof(filetypes.split(','), file.extension.substring(1).tolower()) >= 0);
  hash["filetype"] = file.extension.substring(1);
  hash["filename"] = file.name;
  hash["datetime"] = file.lastwritetime.tostring("yyyy-mm-dd hh:mm:ss");
  dirfilelist.add(hash);
 }
 context.response.addheader("content-type", "application/json; charset=utf-8");
 context.response.write(jsonmapper.tojson(result));
 context.response.end();
 }

 public class namesorter : icomparer
 {
 public int compare(object x, object y)
 {
  if (x == null && y == null)
  {
  return 0;
  }
  if (x == null)
  {
  return -1;
  }
  if (y == null)
  {
  return 1;
  }
  fileinfo xinfo = new fileinfo(x.tostring());
  fileinfo yinfo = new fileinfo(y.tostring());

  return xinfo.fullname.compareto(yinfo.fullname);
 }
 }

 public class sizesorter : icomparer
 {
 public int compare(object x, object y)
 {
  if (x == null && y == null)
  {
  return 0;
  }
  if (x == null)
  {
  return -1;
  }
  if (y == null)
  {
  return 1;
  }
  fileinfo xinfo = new fileinfo(x.tostring());
  fileinfo yinfo = new fileinfo(y.tostring());

  return xinfo.length.compareto(yinfo.length);
 }
 }

 public class typesorter : icomparer
 {
 public int compare(object x, object y)
 {
  if (x == null && y == null)
  {
  return 0;
  }
  if (x == null)
  {
  return -1;
  }
  if (y == null)
  {
  return 1;
  }
  fileinfo xinfo = new fileinfo(x.tostring());
  fileinfo yinfo = new fileinfo(y.tostring());

  return xinfo.extension.compareto(yinfo.extension);
 }
 }

 public bool isreusable
 {
 get
 {
  return true;
 }
 }
}

upload_json.ashx

<%@ webhandler language="c#" class="upload" %>

/**
 * kindeditor asp.net
 * 上传管理
 */

using system;
using system.collections;
using system.web;
using system.io;
using system.globalization;
using litjson;

public class upload : ihttphandler
{
 private httpcontext context;

 public void processrequest(httpcontext context)
 {
 string aspxurl = context.request.path.substring(0, context.request.path.lastindexof("/") + 1);
 
 //文件保存目录路径
 string savepath = "http://www.cnblogs.com/attached/";

 //文件保存目录url
 string saveurl = aspxurl + "http://www.cnblogs.com/attached/";

 //定义允许上传的文件扩展名
 hashtable exttable = new hashtable();
 exttable.add("image", "gif,jpg,jpeg,png,bmp");
 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");

 //最大文件大小
 int maxsize = 1000000;
 this.context = context;

 httppostedfile imgfile = context.request.files["imgfile"];
 if (imgfile == null)
 {
  showerror("请选择文件。");
 }

 string dirpath = context.server.mappath(savepath);
 if (!directory.exists(dirpath))
 {
  showerror("上传目录不存在。");
 }

 string dirname = context.request.querystring["dir"];
 if (string.isnullorempty(dirname)) {
  dirname = "image";
 }
 if (!exttable.containskey(dirname)) {
  showerror("目录名不正确。");
 }

 string filename = imgfile.filename;
 string fileext = path.getextension(filename).tolower();

 if (imgfile.inputstream == null || imgfile.inputstream.length > maxsize)
 {
  showerror("上传文件大小超过限制。");
 }

 if (string.isnullorempty(fileext) || array.indexof(((string)exttable[dirname]).split(','), fileext.substring(1).tolower()) == -1)
 {
  showerror("上传文件扩展名是不允许的扩展名。\n只允许" + ((string)exttable[dirname]) + "格式。");
 }

 //创建文件夹
 dirpath += dirname + "/";
 saveurl += dirname + "/";
 if (!directory.exists(dirpath)) {
  directory.createdirectory(dirpath);
 }
 string ymd = datetime.now.tostring("yyyymmdd", datetimeformatinfo.invariantinfo);
 dirpath += ymd + "/";
 saveurl += ymd + "/";
 if (!directory.exists(dirpath)) {
  directory.createdirectory(dirpath);
 }

 string newfilename = datetime.now.tostring("yyyymmddhhmmss_ffff", datetimeformatinfo.invariantinfo) + fileext;
 string filepath = dirpath + newfilename;

 imgfile.saveas(filepath);

 string fileurl = saveurl + newfilename;

 hashtable hash = new hashtable();
 hash["error"] = 0;
 hash["url"] = fileurl;
 context.response.addheader("content-type", "text/html; charset=utf-8");
 context.response.write(jsonmapper.tojson(hash));
 context.response.end();
 }

 private void showerror(string message)
 {
 hashtable hash = new hashtable();
 hash["error"] = 1;
 hash["message"] = message;
 context.response.addheader("content-type", "text/html; charset=utf-8");
 context.response.write(jsonmapper.tojson(hash));
 context.response.end();
 }

 public bool isreusable
 {
 get
 {
  return true;
 }
 }
}

5.优化改进

使用kindeditor文本编辑器时,发现不能在图片空间中修改已上传图片的信息,删除图片等,也不能进行目录操作,我觉得这是比ckeditor和ckfinder结合的文本编辑器弱势的地方。

大致想了下,有两个方法可以解决:

方法一、独立写一个图片管理的模块,进行可视化操作

方法二、修改plugins/filemanager/filemanager.js,并结合handler进行操作。(这个方法扩展性比较好)

如果有人已经解决了这个问题,希望可以分享一下。

实例下载:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网