Flask項目集成富文本編輯器CKeditor

本文介紹如何在Flask項目中集成富文本編輯器CKeditor,並實現圖片上傳、文件上傳、視頻上傳等功能。javascript

CKeditor是目前最優秀的可見便可得網頁編輯器之一,它採用JavaScript編寫。具有功能強大、配置容易、跨瀏覽器、支持多種編程語言、開源等特色。它很是流行,互聯網上很容易找到相關技術文檔,國內許多WEB項目和大型網站均採用了CKeditor。html

下載CKeditor

訪問CKeditor官方網站,進入下載頁面,選擇Standard Package(通常狀況下功能足夠用了),而後點擊Download CKEditor按鈕下載ZIP格式的安裝文件。若是你想嘗試更多的功能,能夠選擇下載Full Packagejava

下載好CKeditor以後,解壓到Flask項目static/ckeditor目錄便可。python

在Flask項目中使用CKeditor

在Flask項目中使用CKeditor只須要執行兩步就能夠了:git

  1. <script>標籤引入CKeditor主腳本文件。能夠引入本地的文件,也能夠引用CDN上的文件。
  2. 使用CKEDITOR.replace()把現存的<textarea>標籤替換成CKEditor。

示例代碼:編程

html<!DOCTYPE html>
<html>
    <head>
        <title>A Simple Page with CKEditor</title>
        <!-- 請確保CKEditor文件路徑正確 -->
        <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></script>
    </head>
    <body>
        <form>
            <textarea name="editor1" id="editor1" rows="10" cols="80">
                This is my textarea to be replaced with CKEditor.
            </textarea>
            <script>
                // 用CKEditor替換<textarea id="editor1">
                // 使用默認配置
                CKEDITOR.replace('editor1');
            </script>
        </form>
    </body>
</html>

由於CKeditor足夠優秀,因此第二步也可只爲<textarea>追加名爲ckeditorclass屬性值,CKeditor就會自動將其替換。例如:flask

<!DOCTYPE html>
<html>
    <head>
        <title>A Simple Page with CKEditor</title>
        <!-- 請確保CKEditor文件路徑正確 -->
        <script src="{{ url_for('static', filename='ckeditor/ckeditor.js') }}"></script>
    </head>
    <body>
        <form>
            <textarea name="editor1" id="editor1" class="ckeditor" rows="10" cols="80">
                This is my textarea to be replaced with CKEditor.
            </textarea>
        </form>
    </body>
</html>

CKEditor腳本文件也能夠引用CDN上的文件,下面給出幾個參考連接:瀏覽器

  • <script src="//cdn.ckeditor.com/4.4.6/basic/ckeditor.js"></script> 基礎版(迷你版)
  • <script src="//cdn.ckeditor.com/4.4.6/standard/ckeditor.js"></script> 標準版
  • <script src="//cdn.ckeditor.com/4.4.6/full/ckeditor.js"></script> 完整版

開啓上傳功能

默認配置下,CKEditor是沒有開啓上傳功能的,要開啓上傳功能,也至關的簡單,只須要簡單修改配置便可。下面來看看幾個相關的配置值:app

  • filebrowserUploadUrl :文件上傳路徑。若設置了,則上傳按鈕會出如今連接、圖片、Flash對話窗口。
  • filebrowserImageUploadUrl : 圖片上傳路徑。若不設置,則使用filebrowserUploadUrl值。
  • filebrowserFlashUploadUrl : Flash上傳路徑。若不設置,則使用filebrowserUploadUrl值。

爲了方便,這裏咱們只設置filebrowserUploadUrl值,其值設爲/ckupload/(後面會在Flask中定義這個URL)。dom

設置配置值主要使用2種方法:

方法1:經過CKEditor根目錄的配置文件config.js來設置:

javascriptCKEDITOR.editorConfig = function( config ) {
    // ...
    // file upload url
    config.filebrowserUploadUrl = '/ckupload/';
    // ...
};

方法2:將設置值放入做爲參數放入CKEDITOR.replace():

javascript<script>
CKEDITOR.replace('editor1', {
    filebrowserUploadUrl: '/ckupload/',
});
</script>

Flask處理上傳請求

CKEditor上傳功能是統一的接口,即一個接口能夠處理圖片上傳、文件上傳、Flash上傳。先來看看代碼:

pythondef gen_rnd_filename():
    filename_prefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    return '%s%s' % (filename_prefix, str(random.randrange(1000, 10000)))

@app.route('/ckupload/', methods=['POST'])
def ckupload():
    """CKEditor file upload"""
    error = ''
    url = ''
    callback = request.args.get("CKEditorFuncNum")
    if request.method == 'POST' and 'upload' in request.files:
        fileobj = request.files['upload']
        fname, fext = os.path.splitext(fileobj.filename)
        rnd_name = '%s%s' % (gen_rnd_filename(), fext)
        filepath = os.path.join(app.static_folder, 'upload', rnd_name)
        # 檢查路徑是否存在,不存在則建立
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            try:
                os.makedirs(dirname)
            except:
                error = 'ERROR_CREATE_DIR'
        elif not os.access(dirname, os.W_OK):
            error = 'ERROR_DIR_NOT_WRITEABLE'
        if not error:
            fileobj.save(filepath)
            url = url_for('static', filename='%s/%s' % ('upload', rnd_name))
    else:
        error = 'post error'
    res = """

<script type="text/javascript">
  window.parent.CKEDITOR.tools.callFunction(%s, '%s', '%s');
</script>

""" % (callback, url, error)
    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response

上傳文件的獲取及保存部分比較簡單,是標準的文件上傳。這裏主要講講上傳成功後如何回調的問題。

CKEditor文件上傳以後,服務端返回HTML文件,HTML文件包含JAVASCRIPT腳本,JS腳本會調用一個回調函數,若無錯誤,回調函數將返回的URL轉交給CKEditor處理。

這3個參數依次是:

  • CKEditorFuncNum : 回調函數序號。CKEditor經過URL參數提交給服務端
  • URL : 上傳後文件的URL
  • Error : 錯誤信息。若無錯誤,返回空字符串

完整DEMO

這裏有個簡單的DEMO:https://coding.net/u/wtx358/p/flask-ckeditor-demo/git

小結

在以前的文章中,咱們講到了UEditor,就我的感受而言,CKEditor的使用體驗比UEditor好不少,使用方式也比較靈活。但願此文能夠幫助你們在項目中加入優秀的CKEditor編輯器。

原文:http://flask123.sinaapp.com/article/49/

相關文章
相關標籤/搜索