1.什么是KindEditor
KindEditor 是一套開源的在線HTML編輯器,主要用于讓用戶在網(wǎng)站上獲得所見即所得編輯效果,開發(fā)人員可以用 KindEditor 把傳統(tǒng)的多行文本輸入框(textarea)替換為可視化的富文本輸入框。 KindEditor 使用 JavaScript 編寫,可以無縫地與 Java、.NET、PHP、ASP 等程序集成,比較適合在 CMS、商城、論壇、博客、Wiki、電子郵件等互聯(lián)網(wǎng)應(yīng)用上使用。
2.前期準備
到官網(wǎng)下載最新版的KindEditor 4.11,解壓文件后可得
文件結(jié)構(gòu):
asp:與asp結(jié)合的示例代碼
asp.net:與asp.net結(jié)合的示例代碼
attached:上傳文件的根目錄,可在相關(guān)的代碼中修改
examples:功能演示的示例代碼
jsp:與jsp結(jié)合的示例代碼
lang:語言包
php:與php結(jié)合的示例代碼
plugins:控件的功能代碼的實現(xiàn)
kindeditor.js:配置文件
kindeditor-min.js:集成文件
由于使用的是ASP.NET,所以將不需要的文件夾刪掉。其中在asp.net中demo.aspx是參考代碼,也可以刪掉。
3.配置KindEditor
(1)新建網(wǎng)站,將精簡后的kindeditor文件夾放到網(wǎng)站根目錄下下,并且引用kindeditor/asp.net/bin/LitJSON.dll文件。
(2)新建index.aspx文件,引入相關(guān)文件
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,
//設(shè)置編輯器創(chuàng)建后執(zhí)行的回調(diào)函數(shù)
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();
});
},
//上傳文件后執(zhí)行的回調(diào)函數(shù),獲取上傳圖片的路徑
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,一個負責(zé)文件管理,一個負責(zé)上傳管理。你可以根據(jù)自己需求進行相關(guān)修改。
原理:通過實現(xiàn)接口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);
}
}
//根據(jù)path參數(shù),設(shè)置各路徑和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;
ListHashtable> dirFileList = new ListHashtable>();
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]) + "格式。");
}
//創(chuàng)建文件夾
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.優(yōu)化改進
使用KindEditor文本編輯器時,發(fā)現(xiàn)不能在圖片空間中修改已上傳圖片的信息,刪除圖片等,也不能進行目錄操作,我覺得這是比CKEditor和CKFinder結(jié)合的文本編輯器弱勢的地方。
大致想了下,有兩個方法可以解決:
方法一、獨立寫一個圖片管理的模塊,進行可視化操作
方法二、修改plugins/filemanager/filemanager.js,并結(jié)合handler進行操作。(這個方法擴展性比較好)
如果有人已經(jīng)解決了這個問題,希望可以分享一下。
實例下載:KindEditor文本編輯器配置
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- springmvc+kindeditor文件上傳實例詳解
- Kindeditor編輯器添加圖片上傳水印功能(php代碼)
- Kindeditor單獨調(diào)用單圖上傳增加預(yù)覽功能的實例
- Kindeditor單獨調(diào)用多圖上傳實例
- 常用的HTML富文本編譯器UEditor、CKEditor、TinyMCE、HTMLArea、eWebEditor、KindEditor簡介
- js控件Kindeditor實現(xiàn)圖片自動上傳功能
- Kindeditor在線文本編輯器如何過濾HTML
- 使用JavaScript為Kindeditor自定義按鈕增加Audio標簽
- kindeditor編輯器點中圖片滾動條往上頂?shù)腷ug
- kindeditor修復(fù)會替換script內(nèi)容的問題
- Django添加KindEditor富文本編輯器的使用