前端文本框插件KindEditor
阅读原文时间:2023年07月09日阅读:1

KindEditor

1、进入官网

2、下载

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、基本使用

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




文章内容

{{ request.POST.content|safe }}

请输入内容:

{% csrf\_token %}



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 = """

The Dormouse's story


Once upon a time there were three little sisters; and their names were Lacie and Tilffffffffffffflie; and they lived at the bottom of a well.


"""

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 = """

The Dormouse's story


Once upon a time there were three little sisters; and their names were Lacie and Tilffffffffffffflie; and they lived at the bottom of a well.


"""

obj = XSSFilter()  
v = obj.process(html)  
print(v)