阿桂天山的技术小结:Flask+UEditor实现图片文件上传富文本编辑

话不多说,有图有源码

先看效果:

阿桂天山的技术小结:Flask+UEditor实现图片文件上传富文本编辑_第1张图片

阿桂天山的技术小结:Flask+UEditor实现图片文件上传富文本编辑_第2张图片

 1.前端html页面index.html




    
    
    
    
    Ewangda--测试ueditor






2.后端ueditor.py执行文件(这个非常重要)

#encoding: utf-8
from flask import Blueprint,request,jsonify,url_for,send_from_directory,current_app as app
from flask_wtf import CSRFProtect
import json
import re
import string
import time
import hashlib
import random
import base64
import sys
import os

# csrf = CSRFProtect()
os.chdir(os.path.abspath(sys.path[0]))

bp = Blueprint('ueditor',__name__,url_prefix='/ueditor')

UEDITOR_UPLOAD_PATH = ""


@bp.before_app_first_request
def before_first_request():
    global UEDITOR_UPLOAD_PATH

    UEDITOR_UPLOAD_PATH = app.config.get('UEDITOR_UPLOAD_PATH')
    if UEDITOR_UPLOAD_PATH and not os.path.exists(UEDITOR_UPLOAD_PATH):
        os.mkdir(UEDITOR_UPLOAD_PATH)

    # csrf = app.extensions.get('csrf')
    # if csrf:
    #     csrf.exempt(upload)


def _random_filename(rawfilename):
    letters = string.ascii_letters
    random_filename = str(time.time()) + "".join(random.sample(letters,5))
    filename = hashlib.md5(random_filename.encode('utf-8')).hexdigest()
    subffix = os.path.splitext(rawfilename)[-1]
    return filename + subffix

# @csrf.exempt#局部关闭CSRF
@bp.route('/upload/',methods=['GET','POST'])
def upload():
    action = request.args.get('action')
    result = {}
    if action == 'config':
        config_path = os.path.join(bp.static_folder or app.static_folder,'ueditor','config.json')
        #print(config_path)#python project\cms\static\ueditor\config.json
        with open(config_path,'r',encoding='utf-8') as fp:
            result = json.loads(re.sub(r'\/\*.*\*\/','',fp.read()))

    elif action in ['uploadimage','uploadvideo','uploadfile']:
        image = request.files.get("upfile")
        filename = image.filename
        save_filename = _random_filename(filename)
        result = {
            'state': '',
            'url': '',
            'title': '',
            'original': ''
        }
        image.save(os.path.join(UEDITOR_UPLOAD_PATH, save_filename))
        result['state'] = "SUCCESS"
        result['url'] = url_for('ueditor.files', filename=save_filename)
        result['title'] = save_filename
        result['original'] = save_filename

    elif action == 'uploadscrawl':#执行上传涂鸦的action名称
        base64data = request.form.get("upfile")
        img = base64.b64decode(base64data)
        filename = _random_filename('xx.png')
        filepath = os.path.join(UEDITOR_UPLOAD_PATH,filename)
        with open(filepath,'wb') as fp:
            fp.write(img)
        result = {
            "state": "SUCCESS",
            "url": url_for('files',filename=filename),
            "title": filename,
            "original": filename
        }

    return jsonify(result)


@bp.route('/files//')
def files(filename):
    return send_from_directory(UEDITOR_UPLOAD_PATH,filename)

3.路径配置文件config.py

import os

#上传到本地
UEDITOR_UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'static\\images')

4.启动运行程序appstart.py

from flask import Flask,render_template

import config
app = Flask(__name__)
app.config.from_object(config)

from ueditor import bp as ueditor_blue
app.register_blueprint(ueditor_blue)

@app.route('/')
def index():
    return render_template('index.html')
# @app.route('/demo_ueditor')
# def demo_ueditor():
#     return render_template('demo_ueditor.html')

if __name__ == '__main__':
    app.run(port=9000,debug=True)

特殊强调:路径蓝图,必须指向ueditor(这个非常非常非常重要,否则前端会报错),放在app执行文件中

from ueditor import bp as ueditor_blue
app.register_blueprint(ueditor_blue)

5)最后整个工程文件树:

阿桂天山的技术小结:Flask+UEditor实现图片文件上传富文本编辑_第3张图片

 

 希望你能最终实现,对你有用就点赞吧,以鼓励我继续津津乐道!

你可能感兴趣的:(flask,python,后端)