ASP.NET配置KindEditor文字編輯器圖文教程_實用技巧

來源:互聯網
上載者:User

1.什麼是KindEditor

KindEditor 是一套開源的線上HTML編輯器,主要用於讓使用者在網站上獲得所見即所得 (WYSIWYG)編輯效果,開發人員可以用 KindEditor 把傳統的多行文本輸入框(textarea)替換為可視化的富文本輸入框。 KindEditor 使用 JavaScript 編寫,可以無縫地與 Java、.NET、PHP、ASP 等程式整合,比較適合在 CMS、商城、論壇、部落格、Wiki、電子郵件等互連網應用上使用。

2.前期準備

到官網下載最新版的KindEditor 4.11,解壓檔案後可得

檔案結構:

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進行操作。(這個方法擴充性比較好)

如果有人已經解決了這個問題,希望可以分享一下。

執行個體下載:KindEditor文字編輯器配置

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.