最近在项目中经常遇到使用富文本框的情况,当然我们所接触的富文本.框有很多,我个人还是比较偏向于KE(KindEditor)),用起来比较舒服,但是很多新手在用的时候往往会感到不知所措。总感觉API写了很多但是就是不知道怎么去用,今天我就和大家讲讲KE的使用和基本技巧:
如图所示第一个default.css主要是为了修改我们KE的样式,第二个kindeditor-min.js是KE核心功能脚本库,第三个zh_CN.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的界面已经显示出来了,从界面上我们可以看到有很多功能按钮,主要包括对齐、加粗、字体颜色、字体大小等,另外就是我们所经常用到的图片上传表情插入。那么接下来我们看看如何去使用?
下图是初始化的代码相信还有印象吧?红色标记的位置就是本地上传的后台接口地址,这个地址可以由你实际编写的后台上传代码决定。
#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’:’对不起图片上传失败’}
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
至于图片下载到什么地方以及图片是否需要压缩或者裁剪按照平时的处理方式即可。到此为止我们就知道了本地上传的处理,那么有的时候我们会遇到一个问题,那就是我们的图片可能不是来自于本地,而是链接或者是从别的网站上复制粘贴过来的,这个时候我们又该怎么处理呢?
function autoupload() {
var haspicContainer = document.getElementById("has_pic");
if (haspicContainer == null) {
haspicContainer = document.createElement("div");
haspicContainer.id = "has_pic";
haspicContainer.innerHTML = "您有图片需要上传到服务器 上传";
$(".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 + "张图片已经上传成功! 关闭");
}
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
{
///
/// autoupload 的摘要说明
///
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>");