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

本文介绍了如何在Flask应用中集成Ueditor富文本编辑器,包括前端HTML页面的配置、后端Python脚本处理图片和文件上传,以及路径配置和应用启动。关键点在于正确设置蓝图以确保前端请求能正确路由到后端处理。
摘要由CSDN通过智能技术生成

话不多说,有图有源码

先看效果:

 1.前端html页面index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="{{ url_for('static',filename='ueditor/ueditor.config.js') }}"></script>
    <script src="{{ url_for('static',filename='ueditor/ueditor.all.js') }}"></script>
    <script src="{{ url_for('static',filename='ueditor/lang/zh-cn/zh-cn.js') }}"></script>
    <title>Ewangda--测试ueditor</title>
</head>

<body>
<script id="editor" type="text/plain" style="width:80%;height:400px;">
</script>
<script>
    var ue = UE.getEditor("editor",{
        'serverUrl': '/ueditor/upload/'
    });
</script>
</body>
</html>

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/<filename>/')
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)最后整个工程文件树:

 

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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿桂天山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值