1. 程式人生 > >Flask專案整合富文字編輯器CKeditor

Flask專案整合富文字編輯器CKeditor

本文介紹如何在Flask專案中整合富文字編輯器CKeditor,並實現圖片上傳、檔案上傳、視訊上傳等功能。

CKeditor是目前最優秀的可見即可得網頁編輯器之一,它採用JavaScript編寫。具備功能強大、配置容易、跨瀏覽器、支援多種程式語言、開源等特點。它非常流行,網際網路上很容易找到相關技術文件,國內許多WEB專案和大型網站均採用了CKeditor。

下載CKeditor

訪問CKeditor官方網站,進入下載頁面,選擇Standard Package(一般情況下功能足夠用了),然後點選Download CKEditor按鈕下載ZIP格式的安裝檔案。如果你想嘗試更多的功能,可以選擇下載Full Package

下載好CKeditor之後,解壓到Flask專案static/ckeditor目錄即可。

在Flask專案中使用CKeditor

在Flask專案中使用CKeditor只需要執行兩步就可以了:

  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就會自動將其替換。例如:

<!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是沒有開啟上傳功能的,要開啟上傳功能,也相當的簡單,只需要簡單修改配置即可。下面來看看幾個相關的配置值:

  • filebrowserUploadUrl :檔案上傳路徑。若設定了,則上傳按鈕會出現在連結、圖片、Flash對話視窗。
  • filebrowserImageUploadUrl : 圖片上傳路徑。若不設定,則使用filebrowserUploadUrl值。
  • filebrowserFlashUploadUrl : Flash上傳路徑。若不設定,則使用filebrowserUploadUrl值。

為了方便,這裡我們只設置filebrowserUploadUrl值,其值設為/ckupload/(後面會在Flask中定義這個URL)。

設定配置值主要使用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

小結

在之前的文章中,我們講到了UEditor,就個人感覺而言,CKEditor的使用體驗比UEditor好很多,使用方式也比較靈活。希望此文可以幫助大家在專案中加入優秀的CKEditor編輯器。