富文本框KindEditor的使用技巧

富文本框KindEditor的使用技巧

最近在項目中經常遇到使用富文本框的情況,當然我們所接觸的富文本.框有很多,我個人還是比較偏向於KE(KindEditor)),用起來比較舒服,但是很多新手在用的時候往往會感到不知所措。總感覺API寫了很多但是就是不知道怎麼去用,今天我就和大家講講KE的使用和基本技巧:

第一步:我們需要到官網上引用相關的資源包,點擊進入官網下載資源包
第二步:引用資源文件引用相應的JS與CSS文件

如圖所示第一個default.css主要是爲了修改我們KE的樣式,第二個kindeditor-min.js是KE核心功能腳本庫,第三個zh_CN.js是語言漢化的腳本。

第三步:編寫對應html代碼,只需要引入如下代碼即可:
<textarea cols="0" rows="5" name="introduction" class="form-control" id="demo" style="margin: 0px -0.5px 0px 0px; height: 250px; width:100%;">
//這和我們使用的TextArea沒有任何區別,不用寫上非常複雜的html代碼。是不是很簡潔?
</textarea>
第四步:我們需要在JS中初始化控件屬性,以上面的爲例。我們需要寫出如下代碼:
<script type="text/javascript">
 initkindEditor();
 //初始化富文本
 function initkindEditor() {
     KindEditor.ready(function (K) {
         var editor = K.create('#demo', {
             themeType: "simple",
             uploadJson: '../../KEHandler/upload_json.ashx?action=upload_base',
             resizeType: 1,
             pasteType: 2,
             syncType: "",
             filterMode: true,
             allowPreviewEmoticons: false,
             items: [
                    'source', 'undo', 'redo', 'plainpaste', 'wordpaste', 'clearhtml', 'quickformat',
                    'selectall', 'fullscreen', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor',
                    'bold', 'italic', 'underline', 'hr', 'removeformat', '|', 'justifyleft', 'justifycenter',
                    'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'link', 'image',
                    'unlink', 'baidumap', 'emoticons'
                ],
             afterCreate: function () {
                 this.sync();
             },
             afterBlur: function () {
                 this.sync();
             },
             afterChange: function () {
                //富文本輸入區域的改變事件,一般用來編寫統計字數等判斷
                  K('.word_count1').html("最多20000個字符,已輸入" + this.count() + "個字符");
             },
             afterUpload:function(url){
               //上傳圖片後的代碼
             },
             allowFileManager: false,
             allowFlashUpload: false,
             allowMediaUpload: false,
             allowFileUpload: false
         });
     });
 }
我們先來看下運行效果:

KE界面

如圖所示我們可以看到KE的界面已經顯示出來了,從界面上我們可以看到有很多功能按鈕,主要包括對齊、加粗、字體顏色、字體大小等,另外就是我們所經常用到的圖片上傳表情插入。那麼接下來我們看看如何去使用?

第一種:本地上傳圖片至富文本中效果圖如下:
1、點擊上傳圖片按鈕

點擊上傳圖片

2、選擇本地上傳,選擇一張圖片

選擇本地上傳
圖片上傳中

3、圖片上傳完成,選中對應的圖片還可以調整圖片的比例

圖片上傳完成

那麼上傳的代碼究竟是怎麼實現的呢?

下圖是初始化的代碼相信還有印象吧?紅色標記的位置就是本地上傳的後臺接口地址,這個地址可以由你實際編寫的後臺上傳代碼決定。
初始化的代碼

我們看下後臺的代碼是怎麼實現的?
 #region 定義一個方法上傳本地照片
        public void Upload_Native_pic(HttpContext context, string savePath, string website)
        { 
           //定義允許上傳的文件擴展名
           Hashtable extTable = new Hashtable();
           extTable.Add("image", "gif,jpg,jpeg,png,bmp");
           //最大圖片的大小
           int maxSize = 10240000;

           //獲取照片資源
           HttpPostedFile imgFile = context.Request.Files["imgFile"];
           if (imgFile == null)
           {
               showError("請選擇文件。",context);
           }

           if (!Directory.Exists(savePath))
           {
               showError("上傳目錄不存在。",context);
           }
           string dirName = context.Request.QueryString["dir"];
           if (String.IsNullOrEmpty(dirName))
           {
               dirName = "image";
           }
           if (!extTable.ContainsKey(dirName))
           {
               showError("目錄名不正確。",context);
           }
           string fileName = imgFile.FileName;
           string fileExt = Path.GetExtension(fileName).ToLower();
           if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
           {
               showError("上傳文件大小超過限制。",context);
           }
           if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
           {
               showError("上傳文件擴展名是不允許的擴展名。\n只允許" + ((String)extTable[dirName]) + "格式。",context);
           }
           website += dirName + "/";
           savePath += dirName + "/";
           if (!Directory.Exists(savePath))
           {
               Directory.CreateDirectory(savePath);
           }
           String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
           website += ymd + "/";
           savePath+=ymd+"/";
           if (!Directory.Exists(savePath))
           {
               Directory.CreateDirectory(savePath);
           }
           string  newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
           string filePath = savePath + newFileName;
            //圖片路徑
           string  fileUrl = website + newFileName;
           // 開始下載圖片
           new ApplicationUtil().DownLoadNativePIC(imgFile.InputStream, filePath); 

           JSONHelper json = new JSONHelper(); 
           json.AddItem1("error",0);
           json.AddItem("url",fileUrl);
           json.ItemOk();
           string res = json.ToString().Substring(1, json.ToString().Length -2);
           context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
           context.Response.Write(res);
           context.Response.End();
        }
        #endregion

後臺代碼其實就是一個處理圖片上傳的功能,最終返回的的json結構式爲{‘error’:’ ‘,’url’:’ ‘}就可以了,成功的時候error爲0,url爲圖片對應相對地址,錯誤的時候{‘error’:’1’,’message’:’對不起圖片上傳失敗’}

這裏以C#爲例有一點需要注意,那就是返回json的頭部信息需要改爲:

context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
至於圖片下載到什麼地方以及圖片是否需要壓縮或者裁剪按照平時的處理方式即可。到此爲止我們就知道了本地上傳的處理,那麼有的時候我們會遇到一個問題,那就是我們的圖片可能不是來自於本地,而是鏈接或者是從別的網站上覆制粘貼過來的,這個時候我們又該怎麼處理呢?
我們需要額外引入相關的js文件,如下圖所示我們引入一個叫auto.js的文件,這裏我把源碼粘貼上來,在使用的時候只需要將源碼當中的上傳地址修改一下即可
function autoupload() {
    var haspicContainer = document.getElementById("has_pic");
    if (haspicContainer == null) {
        haspicContainer = document.createElement("div");
        haspicContainer.id = "has_pic";
        haspicContainer.innerHTML = "<input type='text' id='piclist' value='' style='display:none;'/><div id='upload'><b>您有圖片需要上傳到服務器</b>&nbsp;&nbsp;<a href='javascript:uploadpic();' >上傳</a></div><div id='confirm'></div>";
        $(".ke-toolbar").after(haspicContainer);
    }

    var img = $(".ke-edit-iframe").contents().find("img");

    var piccount = 0;
    var sstr = "";
    $(img).each(function (i) {
        var that = $(this);
        if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {
            piccount++;
            if (i == $(img).length - 1)
                sstr += that.attr("src");
            else
                sstr += that.attr("src") + "|";
        }
    });

    $("#piclist").val(sstr);
    document.getElementById("has_pic").style.display = (piccount > 0) ? "block" : "none";
}

function closeupload() {
    $("#has_pic").hide();
    $("#upload").show();
}

function uploadpic() {
    var piclist = encodeURI($("#piclist").val());
    if (piclist.length == 0) return false;
    $.ajax({
        url: "../../../Portal/KEHandler/autoupload.ashx",
        data: "pic=" + piclist,
        type: "GET",
        beforeSend: function () {
            $("#upload").hide();
            $("#confirm").text("正在上傳中...");
        },
        success: function (msg) {
            if (msg !== "") {
                var str = new Array();
                str = msg.split('|');
                var img = $(".ke-edit-iframe").contents().find("img");

                $(img).each(function (i) {
                    var that = $(this);
                    if (that.attr("src").indexOf("http://") >= 0 || that.attr("src").indexOf("https://") >= 0) {
                        that.attr("src", "../../../KindEditPic/Aimage/" + str[i]);
                        that.attr("data-ke-src", "../../../KindEditPic/Aimage/" + str[i]);
                    }
                });

                $("#confirm").html(img.length + "張圖片已經上傳成功!&nbsp;&nbsp;<a href='javascript:closeupload();'>關閉</a>");
            }
            else $("#confirm").text("上傳失敗!");
        }
    });
}

我們來看一下後臺代碼是怎麼處理的?因爲我們並不清楚用戶到底複製粘貼了多少張,所以處理的時候我們採用循環來處理,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Globalization;
using System.Net;

namespace WeChat.Portal.KEHandler
{
    /// <summary>
    /// autoupload 的摘要說明
    /// </summary>
    public class autoupload : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string pic = context.Request.QueryString["pic"];

            string[] arr = pic.Split('|');
            string sstr = "";
            UpLoadIMG st = new UpLoadIMG();
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].IndexOf("http://") >= 0 || arr[i].IndexOf("https://") >= 0)
                {
                    string std = st.SaveUrlPics(arr[i], "../../KindEditPic/Aimage/");
                    if (std.Length > 0)
                    {
                        if (i == arr.Length - 1)
                            sstr += std;
                        else
                            sstr += std + "|";
                    }
                }
            }
            context.Response.Write(sstr);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class UpLoadIMG
    {
        public string SaveUrlPics(string imgurlAry, string path)
        {
            string strHTML = "";
            string dirPath = HttpContext.Current.Server.MapPath(path);

            try
            {
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
                dirPath += ymd + "/";
                if (!Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }
                string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + imgurlAry.Substring(imgurlAry.LastIndexOf("."));

                WebClient wc = new WebClient();
                wc.DownloadFile(imgurlAry, dirPath + newFileName);
                strHTML = ymd + "/" + newFileName;
            }
            catch (Exception ex)
            {
                //return ex.Message;
            }
            return strHTML;
        }
    }
}

至此我們就全部處理完畢了,不管是複製粘貼的圖片還是本地上傳的圖片全部都可以使用了,最後告訴大家怎麼取值怎麼複製吧?

取值:

//點擊按鈕獲取富文本的值
 $("#ke-button").on("click", function () {
     //獲取富文本輸入框的值
     var htmlStr = KindEditor.instances[0].html().trim();
     console.log("未加密:\n" + htmlStr);
     console.log("加密:\n" + escape(htmlStr));
 })

賦值:

KindEditor.instances[0].html("<p style='color:red'>夏守成<p>");

如果大家有任何疑問或者不清楚的地方直接留言或者評論即可!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章