Asp. NET configuration kindeditor Text Editor Graphic Tutorial _ Practical Tips

Source: Internet
Author: User
Tags hash httpcontext tojson

1. What is Kindeditor

Kindeditor is an open source online HTML editor, designed to allow users to get WYSIWYG editing on the site, and developers can replace the traditional multiline text input box (TEXTAREA) with Kindeditor with a visual rich text input box. Kindeditor is written using JavaScript, seamless integration with Java,. NET, PHP, ASP and other programs, more suitable for CMS, shopping malls, forums, blogs, wikis, e-mail and other Internet applications to use.

2. Preliminary preparation

To the official website download the latest version of Kindeditor 4.11, extract the file can be

File structure:

asp: Sample code in conjunction with ASP

asp.net: Sample code combined with ASP.net

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

Examples: Sample code for feature demo

JSP: Sample code in conjunction with JSP

Lang: Language pack

PHP: Sample code combined with PHP

Plugins: Implementation of the control's functional code

Kindeditor.js: Configuration file

Kindeditor-min.js: Integrated Files

Because of the use of ASP.net, you will not need to delete the folder. In the ASP.net, demo.aspx is the reference code, can also be deleted.

3. Configure Kindeditor

(1) Create a new Web site, place the streamlined Kindeditor folder under the root directory of the Web site, and refer to the Kindeditor/asp.net/bin/litjson.dll file.

(2) New Index.aspx file, introduction of relevant documents

 <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 (' #con Tent ', {//Upload management Uploadjson: ' Kindeditor/asp.net/upload_json.ashx ',//File Management Filemanagerjson: ' Kindeditor/asp.net/fil
   E_manager_json.ashx ', allowfilemanager:true,//Set callback function executed after editor creation aftercreate:function () {var self = this;
   K.ctrl (document, function () {self.sync ();
   K (' form[name=example] ') [0].submit ();
   });
   K.ctrl (Self.edit.doc, function () {self.sync ();
   K (' form[name=example] ') [0].submit ();
  });
  The callback function that executes after uploading the file, gets the path of the uploaded image afterupload:function (URL) {alert (URL); },//editor HighDegree width: ' 700px ',//editor width height: ' 450px; ',///Configuration Editor's toolbar items: [' source ', ' | ', ' undo ', ' Redo ', ' | ', ' preview ' , ' print ', ' template ', ' Code ', ' Cut ', ' copy ', ' Paste ', ' plainpaste ', ' wordpaste ', ' | ', ' justifyleft ', ' justifycenter ', ' Justifyright ', ' justifyfull ', ' insertorderedlist ', ' insertunorderedlist ', ' Indent ', ' outdent ', ' subscript ', ' SUPERSCR IPT ', ' clearhtml ', ' Quickformat ', ' selectall ', ' | ', ' fullscreen ', '/', ' formatblock ', ' fontname ', ' fontsize ', ' | ', ' fore Color ', ' hilitecolor ', ' bold ', ' italic ', ' underline ', ' strikethrough ', ' lineheight ', ' removeformat ', ' | ', ' image ', ' mult Iimage ', ' flash ', ' media ', ' insertfile ', ' table ', ' hr ', ' emoticons ', ' baidumap ', ' pagebreak ', ' anchor ', ' link ', ' Unlin
  K ', ' | ', ' about ']};
 Prettyprint ();
 });
 </script>

(3) Add a TextBox control to the page, name the ID content, and change the property "TextMode" property 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 browser

4. Attachment Upload principle

There are two important file_manager_json.ashx,upload_json.ashx in the ASP.net folder, one for file management and one for upload management. You can make relevant changes according to your own needs.

principle: to take over HTTP requests by implementing interface IHttpHandler.

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 URL, you can specify an absolute path, such as http://www.yoursite.com/attached/String Rooturl = Aspxurl + "http://www.cnblogs.com/attached/";

 Picture 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 based on 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, @ "(. *?)
 [^\/]+\/$ "," $ "); }//Sort form, name or size String order = context.
 request.querystring["Order"]; Order = String.IsNullOrEmpty (order)? "": Order.

 ToLower (); Not allowed to use.
 Move to the previous level of the 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 (); }//directory does not exist or is not a directory if (! Directory.Exists (Currentpath)) {context.
  Response.Write ("Directory does not exist."); Context.
 Response.End ();
 }//Traverse directory to obtain file information 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 

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);

 File save directory path String savepath = "http://www.cnblogs.com/attached/";

 File save Directory URL String saveurl = aspxurl + "http://www.cnblogs.com/attached/";
 Defines the file extensions allowed to be uploaded 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 ("Please select a file.")
 "); String Dirpath = context.
 Server.MapPath (Savepath); if (! Directory.Exists (Dirpath)) {showerror ("Upload directory does not exist.
 "); String dirname = context.
 request.querystring["dir"];
 if (String.IsNullOrEmpty (dirname)) {dirname = "image"; } if (!exttable.containskey (dirname)) {showerror ("directory name is not correct.")
 ");
 String fileName = imgfile.filename; String Fileext = path.getextension (fileName).

 ToLower (); if (Imgfile.inputstream = null | | imgFile.InputStream.Length > MaxSize) {showerror ("Upload file size exceeds limit.")
 "); } if (String.IsNullOrEmpty (fileext) | | Array.indexof ((((String) exttable[dirname]). Split (', '), fileext.substring (1). ToLower () = = = 1) {showerror ("The Upload file extension is an disallowed extension.") \ nthe only "+ ((String) exttable[dirname]) +" format is allowed.
 ");
 //Create 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 {true;
 }
 }
}

5. Optimization and improvement

When using the Kindeditor text editor, I found that it was not possible to modify the uploaded images in the picture space, delete the pictures, etc., or do the directory operation, which I think is a weaker place than the text editor combined with CKEditor and Ckfinder.

In general, there are two ways to solve this problem:

method One, The independent writing a picture management module, carries on the visualization operation

method Two, modify Plugins/filemanager/filemanager.js, and combine handler to carry on operation. (This method is better extensibility)

If someone has solved the problem, I hope we can share it.

Instance Downloads: Kindeditor Text editor configuration

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.