三部分:
html中加入editor,然后js引入ckeditor,并且进行编辑器替换,需要添加上传图片的路由
在py主程序中进行路由设置、图片存储、路径交互
在对应的文件夹创建一个目录。
html页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CKEditor</title>
<script src="//cdn.ckeditor.com/4.5.3/standard/ckeditor.js"></script>
</head>
<body>
<textarea name="editor1"></textarea>
<script>
CKEDITOR.replace( 'editor1', {
filebrowserImageUploadUrl: '/ckupload/'
});
</script>
</body>
</html>
主程序:
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 = """<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
if __name__ == '__main__':
app.run()
路径结构:
参考:
https://github.com/gustitammam/Flask-CKEditor-upload-image