ASP.NET配置KindEditor文本編輯器 【轉載】

以前一直使用CKEditorCKFinder結合的文本編輯器,偶然機會看到KindEditor,感受界面挺好看的,示例代碼比較多,API文檔內容清晰簡單,因而下載嘗試用下。javascript

 

1.什麼是KindEditorphp

KindEditor 是一套開源的在線HTML編輯器,主要用於讓用戶在網站上得到所見即所得編輯效果,開發人員能夠用 KindEditor 把傳統的多行文本輸入框(textarea)替換爲可視化的富文本輸入框。 KindEditor 使用 JavaScript 編寫,能夠無縫地與 Java、.NET、PHP、ASP 等程序集成,比較適合在 CMS、商城、論壇、博客、Wiki、電子郵件等互聯網應用上使用。css

 

2.前期準備html

到官網下載最新版的KindEditor 4.11,解壓文件後可得java

文件結構:web

asp:與asp結合的示例代碼json

asp.net:與asp.net結合的示例代碼瀏覽器

attached:上傳文件的根目錄,可在相關的代碼中修改app

examples:功能演示的示例代碼asp.net

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;
        }
    }
}
View Code

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;
        }
    }
}
View Code

5.優化改進

使用KindEditor文本編輯器時,發現不能在圖片空間中修改已上傳圖片的信息,刪除圖片等,也不能進行目錄操做,我以爲這是比CKEditor和CKFinder結合的文本編輯器弱勢的地方。

大體想了下,有兩個方法能夠解決:

一是:獨立寫一個圖片管理的模塊,進行可視化操做

二是:修改plugins/filemanager/filemanager.js,並結合handler進行操做。(這個方法擴展性比較好)

若是有人已經解決了這個問題,發個參考例子給我把,謝謝!!

如上述有什麼不清晰的,能夠去官網參考下!KindEditor

相關文章
相關標籤/搜索