前端文本框插件KindEditor


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)


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM