python ckeditor上传图片功能

三部分:

html中加入editor,然后js引入ckeditor,并且进行编辑器替换,需要添加上传图片的路由

在py主程序中进行路由设置、图片存储、路径交互

在对应的文件夹创建一个目录。

html页面: 



    
        
        CKEditor
        
    
    
        
        
    

 

主程序:

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

app = Flask(__name__)
app.debug = True

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('/')
def index():
    return render_template('index.html')


@app.route('/ckupload/', methods=['POST', 'OPTIONS'])
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(current_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 = """""" % (callback, url, error)
    response = make_response(res)
    response.headers["Content-Type"] = "text/html"
    return response

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

路径结构:

python ckeditor上传图片功能_第1张图片

参考:

https://github.com/gustitammam/Flask-CKEditor-upload-image

你可能感兴趣的:(python ckeditor上传图片功能)