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/

相关文章
相关标签/搜索