1. 程式人生 > >Flask學習10:Flask專案整合富文字編輯器CKEditor 上傳圖片

Flask學習10:Flask專案整合富文字編輯器CKEditor 上傳圖片

CKEditor下載地址:https://ckeditor.com/ckeditor-4/download/
訪問CKeditor官方網站,進入下載頁面,選擇Standard Package(一般情況下功能足夠用了),如果你想嘗試更多的功能,可以選擇下載Full Package。
下載好CKeditor之後,解壓到Flask專案static/ckeditor目錄即可。

在Flask專案中整合CKEditor:

  1. <scripts>標籤中匯入CKEditor
  2. 使用CKEDITOR.replace()把現存的<textarea>替換成CKEditor

程式碼如下:

<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {# 引入CKEditor#} <script type="text/javascript" src="../static/js/ckeditor/ckeditor.js"></script> </head> <body> <form method="post" action="
{{ url_for('ckupload') }}
" enctype="multipart/form-data"> <input type="text" name="subject" placeholder="主題"> <textarea name="content" id="content" placeholder="內容"></textarea> <input type="submit" value="立即釋出"> {# 替換textarea#} <script type="text/javascript"
>
CKEDITOR.replace('content', { {# 開啟上傳功能,配置上傳路徑#} filebrowserUploadUrl: '/ckupload/', }); </script> </form> </body> </html>

Flask處理上傳請求:

CKEditor上傳功能是統一的介面,即一個介面可以處理圖片上傳、檔案上傳、Flash上傳。先來看看程式碼:

from flask import Flask, render_template, request, make_response, url_for
from flask_script import Manager
import datetime
import os
import random

app = Flask(__name__)
manager = Manager(app)

def 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

@app.route('/', methods=['POST', 'GET'])
def index():
    return render_template('index.html')

if __name__ == '__main__':
    manager.run()

再去看自己專案的目錄,就可以找到/upload底下已經有自己上傳的圖片了。