ASP. NET configuration KindEditor text editor graphic tutorial,

Source: Internet
Author: User
Tags tojson

ASP. NET configuration KindEditor text editor graphic tutorial,

1. What is KindEditor?

KindEditor is an open-source online HTML editor. It is mainly used to enable users to obtain WYSIWYG editing results on the website. developers can use KindEditor to input traditional multi-line text boxes (textarea) replace it with a visualized rich text input box. KindEditor is written in JavaScript and can be seamlessly integrated with Java ,.. NET, PHP, ASP, and other programs are suitable for use in Internet applications such as CMS, mall, forum, blog, Wiki, and email.

2. Preparations

Download the latest KindEditor 4.11 from the official website. Unzip the file and you can find it.

File structure:

Asp: Sample Code combined with asp

Asp.net: Sample Code combined with asp.net

Attached: root directory of the uploaded file, which can be modified in the relevant code

Examples: Sample Code for function demonstration

Jsp: Sample Code combined with jsp

Lang: Language Pack

Php: Sample Code combined with php

Plugins: Implementation of functional code of controls

Kindeditor. js: Configuration File

Kindeditor-min.js: Integration files

Because ASP. NET is used, remove unnecessary folders. In asp.net, demo. aspx is the reference code and can be deleted.

3. Configure KindEditor

(1) create a new website, put the simplified kindeditor folder under the root directory of the website, and reference the kindeditor/asp.net/bin/litjson.dllfile.

(2) create an index. aspx file and introduce relevant files.

<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/pretplugin. js "type =" text/javascript "> </script> <script type =" text/javascript "> KindEditor. ready (function (K) {var editor = K. create ('# content', {// upload management uploadJson: 'kindeditor/asp.net/upload_json.ashx', // file management fileManagerJson: 'kindeditor/plugin, allowFileManager: true, // set the callback function 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 () ;}) ;}, // callback function executed after the file is uploaded to obtain the path of the uploaded image afterUpload: function (url) {alert (url );}, // editor height width: '700px ', // editor width height: '0000px;', // configure the editor toolbar 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', 'strikethangout', 'lineheight ', 'removeformat', '|', 'image', 'multiimage', 'flash', 'Media ', 'insertfile', 'table', 'hr', 'emoticons ', 'baidumap', 'pagebreak', 'anchor ', 'link', 'unlink',' | ', 'about']}); prettyPrint ();}); </script>

(3) Add a textbox Control to the page, name the id as content, and change the attribute "TextMode" to 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) view in a browser

4. Attachment upload Principle

In the asp.net folder, there are two important file_manager_json.ashx and upload_json.ashx. One is responsible for file management and the other is responsible for upload management. You can make modifications as needed.

Principle:Use the IHttpHandler interface to take over HTTP requests.

File_manager_json.ashx

<% @ Webhandler Language = "C #" class = "FileManager" %>/*** KindEditor ASP. NET * file management */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); // root directory path, relative path: String rootPath =" http://www.cnblogs.com/attached/ "; // Root directory URL, which can specify an absolute path, for example http://www.yoursite.com/attached/ String rootUrl = aspxUrl +" http://www.cnblogs.com/attached/ "; // Image extension 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) ;}// set the path and URL String path = context according to the path parameter. 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 ");} // sorting format, name or size or type String order = context. request. queryString ["order"]; order = String. isNullOrEmpty (order )? "": Order. toLower (); // cannot be used .. move to the upper-level directory if (Regex. isMatch (path ,@"\. \. ") {context. response. write ("Access is not allowed. "); context. response. end ();} // The last character is not/if (path! = ""&&! Path. endsWith ("/") {context. response. write ("Parameter is not valid. "); context. response. end ();} // The directory does not exist or is not the directory if (! Directory. exists (currentPath) {context. response. write ("Directory does not exist. "); context. response. end () ;}// retrieve the file information by traversing the Directory 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; charsets = 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 * upload management */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); // path of the file storage directory String savePath =" http://www.cnblogs.com/attached/ "; // File Save directory URL String saveUrl = aspxUrl +" http://www.cnblogs.com/attached/ "; // Defines the file extension 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 "); // maximum file size: int maxSize = 1000000; this. context = context; HttpPostedFile imgFile = context. request. files ["imgFile"]; If (imgFile = null) {showError ("select a file. ");} String dirPath = context. Server. MapPath (savePath); if (! Directory. Exists (dirPath) {showError ("the upload Directory does not exist. ");} String dirName = context. Request. QueryString [" dir "]; if (String. IsNullOrEmpty (dirName) {dirName =" image ";} if (! ExtTable. ContainsKey (dirName) {showError ("the directory name is incorrect. ");} String fileName = imgFile. fileName; String fileExt = Path. getExtension (fileName ). toLower (); if (imgFile. inputStream = null | imgFile. inputStream. length> maxSize) {showError ("the size of the uploaded file exceeds the limit. ");} If (String. isNullOrEmpty (fileExt) | Array. indexOf (String) extTable [dirName]). split (','), fileExt. substring (1 ). toLower () =-1) {showError ("the file extension is not allowed. \ N only supports the "+ (String) extTable [dirName]) +" format. ") ;}// Create the folder 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. Optimization and Improvement

When you use the KindEditor text editor, you cannot modify the information of uploaded images, delete images, or perform directory operations in the image space, I think this is worse than the text editor that combines CKEditor and CKFinder.

There are two solutions to this problem:

Method 1,Write an image management module for visualization.

Method 2,Modify plugins/filemanager. js and operate with handler. (This method is highly scalable)

If someone has solved this problem, I hope you can share it with me.

Download an instance: KindEditor text editor configuration

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.