KindEditor

 

1、进入官网

2、下载

  • 官网下载:http://kindeditor.net/down.php
  • 本地下载:http://files.cnblogs.com/files/wupeiqi/kindeditor_a5.zip

3、文件夹说明

├── asp                          asp示例
├── asp.net asp.net示例
├── attached 空文件夹,放置关联文件attached
├── examples HTML示例
├── jsp java示例
├── kindeditor-all-min.js 全部JS(压缩)
├── kindeditor-all.js 全部JS(未压缩)
├── kindeditor-min.js 仅KindEditor JS(压缩)
├── kindeditor.js 仅KindEditor JS(未压缩)
├── lang 支持语言
├── license.txt License
├── php PHP示例
├── plugins KindEditor内部使用的插件
└── themes KindEditor主题

4、基本使用

<textarea name="content" id="content"></textarea>

<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
}); function initKindEditor() {
var kind = KindEditor.create('#content', {
width: '100%', // 文本框宽度(可以百分比或像素)
height: '300px', // 文本框高度(只能像素)
minWidth: 200, // 最小宽度(数字)
minHeight: 400 // 最小高度(数字)
       // 更多见 http://kindeditor.net/docs/option.html

});
}
</script>

5、详细参数

  http://kindeditor.net/docs/option.html

  重点说明几个常用的解释一下:

  items:配置编辑器的工具栏中显示哪些工具,其中”/”表示换行,”|”表示分隔符。 示例: items: [ 'source', '|', 'undo', 'redo', ]

  noDisableItems:不禁用的工具项,需要依赖designMode:false 起效。示例:

  filterMode:防范XSS攻击,对输入代码进行过滤,值为false的时候允许所有html标签。默认为true,只允许一些指定的html标签输入&保存

  wellFormatMode:true时美化HTML数据。默认true

  resizeType:2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动。

  themeType:指定主题风格,可设置”default”、”simple”,指定simple时需要引入simple.css。默认值default

  useContextmenu:true时使用右键菜单,false时屏蔽右键菜单

  syncType:同步数据的方式,可设置”“、”form”,值为form时提交form时自动同步,空时不会自动同步。

  uploadJson:指定上传文件的服务器端程序(POST 请求url路径)。 举例:uploadJson: '/upload_file/', 上传到:  http://127.0.0.1:8000/upload_file/?dir=image

  allowImageUpload:true时显示图片上传按钮。

allowFlashUpload:true时显示Flash上传按钮。

  allowMediaUpload:true时显示视音频上传按钮。

  allowFileUpload:true时显示文件上传按钮。

  allowFileManager:true时显示浏览远程服务器按钮。文件管理:默认false

   autoHeightMode:值为true,并引入autoheight.js插件时自动调整高度。

  fileManagerJson:指定浏览远程图片的服务器端程序。即访问文件管理的URL路径

    extraFileUploadParams:上传图片、Flash、视音频、文件时,支持添加别的参数一并传到服务器。

  例如CSRF参数:

extraFileUploadParams: {
'csrfmiddlewaretoken': '{{ csrf_token }}',
},
  
filePostName:指定上传文件form名称。

6、上传文件示例

  django 渲染模板 html

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body> <div>
<h1>文章内容</h1>
{{ request.POST.content|safe }}
</div> <form method="POST">
<h1>请输入内容:</h1>
{% csrf_token %}
<div style="width: 500px; margin: 0 auto;">
<textarea name="content" id="content"></textarea>
</div>
<input type="submit" value="提交"/>
</form> <script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
}); function initKindEditor() {
var a = 'kind';
var kind = KindEditor.create('#content', {
width: '100%', // 文本框宽度(可以百分比或像素)
height: '300px', // 文本框高度(只能像素)
minWidth: 200, // 最小宽度(数字)
minHeight: 400, // 最小高度(数字)
uploadJson: '/kind/upload_img/',
extraFileUploadParams: {  // 上传图片是需要设置。单个图片上传这里采用的是form + iframe 实现的,djanjo 处理时 form表单需要提交csrfmiddlewaretoken的csrftoken
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
fileManagerJson: '/kind/file_manager/',
allowPreviewEmoticons: true,  //允许表情预览
allowImageUpload: true  //显示图片上传按钮
});
}
</script>
</body>
</html>

django - views.py

文件上传

from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.views import View import json
import os
from io import BytesIO from utils.check_code import create_validate_code # Create your views here.
class UploadFile(View):
def get(self, request):
pass def post(self, request):
"""
文件上传
:param request:
:return:
"""
print(request.FILES)
file = request.FILES.get('imgFile')
SUB_DIR = request.get_full_path().split("=")[1]
print(SUB_DIR)
UPLOAD_BASE_DIR = 'static/upload_file/'
save_uri = UPLOAD_BASE_DIR + SUB_DIR + 's/' + file.name
print(save_uri)
with open(save_uri, 'wb') as f:
for items in file.chunks():
f.write(items)
dic = {
'error': 0,   // 为0表示上传无误
'url': '/' + save_uri,   //返回文件地址,前端获取用来生成img标签
'message': '错误了...'

}

ret = HttpResponse(json.dumps(dic))
ret['X-Frame-Options'] = None    //此参数默认为deny 浏览器会禁止解析展示
return ret class Kind(View):
def get(self, request): return render(request, 'kindeditor/simple1.html')

文件管理

class FileManager(View):
def get(self, request):
dic = {}
root_path = 'D:/Python3_study/s14day19_2/static/upload_file/' # 代码所在操作系统存储文件的绝对路径
static_root_path = '/static/upload_file/' # 请求url文件基础路径
request_path = request.GET.get('path')
if request_path:
print('获取到请求路径:', request_path)
abs_current_dir_path = os.path.join(root_path, request_path)
# 获取当前请求路径的上一级目录名:
# 1.如果当前请求路径是第一级目录,则上一级目录为空字符串,即:文件管理根目录。
# 2.如果当前请求路径是二级以上子目录,则会有上一级目录名
move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path else:
abs_current_dir_path = root_path
# 如果请求路径为文件管理的根目录,则上一级目录
dic['moveup_dir_path'] = '' dic['current_dir_path'] = request_path
dic['current_url'] = os.path.join(static_root_path, request_path)
print('current_url:', dic.get('current_url'))
print('current_dir_path:', dic.get('current_dir_path'))
print('moveup_dir_path:', dic.get('moveup_dir_path')) file_list = []
for item in os.listdir(abs_current_dir_path):
# 获取当前文件/文件夹的绝对路径
abs_item_path = os.path.join(abs_current_dir_path, item)
# 获取文件的扩展名(将文件路径和 . 后面的扩展名分开;如果是目录,则扩展名为空字符串)
a, exts = os.path.splitext(item)
# 判断当前项目是否为目录
is_dir = os.path.isdir(abs_item_path)
if is_dir:
temp = {
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': item,
# 创建时间
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
else:
temp = {
'is_dir': False,
'has_file': False,
'filesize': os.stat(abs_item_path).st_size, # 文件大小
'dir_path': '',
'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False, # 是否为图片
'filetype': exts.lower().strip('.'),
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
} file_list.append(temp)
dic['file_list'] = file_list
return HttpResponse(json.dumps(dic))

7、XSS过滤特殊标签

处理依赖

pip3 install beautifulsoup4

XSS示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup class XSSFilter(object):
__instance = None def __init__(self):
# XSS白名单
self.valid_tags = {
"font": ['color', 'size', 'face', 'style'],
'b': [],
'div': [],
"span": [],
"table": [
'border', 'cellspacing', 'cellpadding'
],
'th': [
'colspan', 'rowspan'
],
'td': [
'colspan', 'rowspan'
],
"a": ['href', 'target', 'name'],
"img": ['src', 'alt', 'title'],
'p': [
'align'
],
"pre": ['class'],
"hr": ['class'],
'strong': []
} @classmethod
def instance(cls):
if not cls.__instance:
obj = cls()
cls.__instance = obj
return cls.__instance def process(self, content):
soup = BeautifulSoup(content, 'lxml')
# 遍历所有HTML标签
for tag in soup.find_all(recursive=True):
# 判断标签名是否在白名单中
if tag.name not in self.valid_tags:
tag.hidden = True
if tag.name not in ['html', 'body']:
tag.hidden = True
tag.clear()
continue
# 当前标签的所有属性白名单
attr_rules = self.valid_tags[tag.name]
keys = list(tag.attrs.keys())
for key in keys:
if key not in attr_rules:
del tag[key] return soup.renderContents() if __name__ == '__main__':
html = """<p class="title">
<b>The Dormouse's story</b>
</p>
<p class="story">
<div name='root'>
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
and they lived at the bottom of a well.
<script>alert(123)</script>
</div>
</p>
<p class="story">...</p>""" v = XSSFilter.instance().process(html)
print(v)
基于__new__实现单例模式示例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup class XSSFilter(object):
__instance = None def __init__(self):
# XSS白名单
self.valid_tags = {
"font": ['color', 'size', 'face', 'style'],
'b': [],
'div': [],
"span": [],
"table": [
'border', 'cellspacing', 'cellpadding'
],
'th': [
'colspan', 'rowspan'
],
'td': [
'colspan', 'rowspan'
],
"a": ['href', 'target', 'name'],
"img": ['src', 'alt', 'title'],
'p': [
'align'
],
"pre": ['class'],
"hr": ['class'],
'strong': []
} def __new__(cls, *args, **kwargs):
"""
单例模式
:param cls:
:param args:
:param kwargs:
:return:
"""
if not cls.__instance:
obj = object.__new__(cls, *args, **kwargs)
cls.__instance = obj
return cls.__instance def process(self, content):
soup = BeautifulSoup(content, 'lxml')
# 遍历所有HTML标签
for tag in soup.find_all(recursive=True):
# 判断标签名是否在白名单中
if tag.name not in self.valid_tags:
tag.hidden = True
if tag.name not in ['html', 'body']:
tag.hidden = True
tag.clear()
continue
# 当前标签的所有属性白名单
attr_rules = self.valid_tags[tag.name]
keys = list(tag.attrs.keys())
for key in keys:
if key not in attr_rules:
del tag[key] return soup.renderContents() if __name__ == '__main__':
html = """<p class="title">
<b>The Dormouse's story</b>
</p>
<p class="story">
<div name='root'>
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
and they lived at the bottom of a well.
<script>alert(123)</script>
</div>
</p>
<p class="story">...</p>""" obj = XSSFilter()
v = obj.process(html)
print(v)

前端文本框插件KindEditor的更多相关文章

  1. 常用的富文本框插件FreeTextBox、CuteEditor、CKEditor、FCKEditor、TinyMCE、KindEditor ;和CKEditor实例

    http://www.cnblogs.com/cxd4321/archive/2013/01/30/2883078.html 目前市面上用的比较多的富文本编辑器有: FreeTextBox 一个有很多 ...

  2. Extjs4.2x与富文本框编辑器KindEditor的整合

    Extjs4本身的HtmlEditor编辑器,太鸡肋了,简单的html能够应付一下,稍加复杂的就无能为力了. 对于Extjs的HtmlEditor扩展主要有三个方向,一个是扩展其本身的htmlEdit ...

  3. ASP.NET中使用附文本框插件

    使用附文本选项框插件步骤 Newtonsoft.Json 改变js的配置文件的url 最后一定要关闭页面中的 ValidateRequest=false

  4. aspx使用KindEditor副文本框插件出现检测到有潜在危险

    web配置添加    <httpRuntime requestValidationMode="2.0" /> aspx页面添加   ValidateRequest=&q ...

  5. H5页面设计器,仿有赞商城页面在线设计器,比富文本框更友好的内容编辑器

    基本上每个web应用,都会牵扯到内容编辑,尤其是移动的web应用,微信开发之类的.页面内容自定义是最常用的功能了,之前大部分解决方案都是采用富文本框编辑器kindeditor,ueditor,cked ...

  6. MVC动态添加文本框,后台使用FormCollection接收

    在"MVC批量添加,增加一条记录的同时添加N条集合属性所对应的个体"中,对于前台传来的多个TextBox值,在控制器方法中通过强类型来接收.使用FormCollection也可以接 ...

  7. input文本框默认提示

    今天闲暇时间把自己以前写的一个文本框默认提示函数改成了一个小插件.下面是代码 1.引入jQuery库 <script src="http://code.jquery.com/jquer ...

  8. 基于bootstrap的富文本框——wangEditor【欢迎增加开发】

    先来一张效果图: 01. 引言 老早就開始研究富文本框的东西,在写完<深入理解javascript原型与闭包>之后,就想着要去做一个富文本框的插件的样例. 如今网络上开源的富文本框插件许多 ...

  9. 使用 jquery-autocomplete插件 完成文本框输入自动填充联想效果 解决兼容IE输入中文问题

    项目中有时会用到ajax自动补全查询,就像Google的搜索框中那样,输入汉字或者字母的首个字母,则包含这个汉字或者字母的相关条目会显示出来供用户选择,该插件就是实现这样的功能的.autocomple ...

随机推荐

  1. 洛谷 P3647 [APIO2014]连珠线(换根 dp)

    题面传送门 题意: 桌子上有 \(1\) 个珠子,你要进行 \(n-1\) 次操作,每次操作有以下两种类型: 拿出一个新珠子,并选择一个桌子上的珠子,在它们之间连一条红线 选择两个由红线相连的珠子 \ ...

  2. 洛谷 P4621 - [COCI2012-2013#6] BAKTERIJE(exCRT)

    洛谷题面传送门 发篇正常点的题解. 首先对于这样的题暴力枚举肯定是不行的,因为最小时间显然可能达到 \((4nm)^5\approx 10^{20}\),就算数据很难卡到这个上界,构造出一些使你暴力超 ...

  3. 中兴交换机基础配置(备份、dhcp中继、monitor)

    1. 备份配置 格式: copy tftp/sftp/ftp [vrf mng] root: 本地文件 远端文件 1. 通过tftp进行备份,vrf mng表示指定使用管理口链路连接 copy tft ...

  4. kubernetes部署 flannel网络组件

    创建 flannel 证书和私钥flannel 从 etcd 集群存取网段分配信息,而 etcd 集群启用了双向 x509 证书认证,所以需要为 flanneld 生成证书和私钥. cat > ...

  5. 『学了就忘』Linux文件系统管理 — 67、通过命令模式进行LVM分区

    目录 1.物理卷管理 (1)准备硬盘或者分区 (2)建立物理卷 (3)查看物理卷 (3)删除物理卷 2.创建卷组 (1)建立卷组 (2)查看卷组 (3)增加卷组容量 (4)减小卷组容量 (5)删除卷组 ...

  6. 源码分析-NameServer

    架构设计 消息中间件的设计思路一般是基于主题订阅发布的机制,消息生产者(Producer)发送某一个主题到消息服务器,消息服务器负责将消息持久化存储,消息消费者(Consumer)订阅该兴趣的主题,消 ...

  7. 13个酷炫的JavaScript一行程序

    1. 获得一个随机的布尔值(true/false) const randomBoolean = () => Math.random() >= 0.5; console.log(random ...

  8. 手淘lib-flexible布局适配方案

    前置知识:什么是rem CSS3新增的一个相对单位rem(root em,根em).rem是相对于根节点(或者是html节点).如果根节点设置了font-size:10px;那么font-size:1 ...

  9. 【2021赣网杯web(一)】gwb-web-easypop

    源码分析 <?php error_reporting(0); highlight_file(__FILE__); $pwd=getcwd(); class func { public $mod1 ...

  10. canal整合springboot实现mysql数据实时同步到redis

    业务场景: 项目里需要频繁的查询mysql导致mysql的压力太大,此时考虑从内存型数据库redis里查询,但是管理平台里会较为频繁的修改增加mysql里的数据 问题来了: 如何才能保证mysql的数 ...