You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask Admin集成CKEditor后图片上传功能异常求助

Flask-CKEditor + Flask-Admin 图片上传功能修复方案

1. 修正模板中的CKEditor配置

你的模板里ckeditor.config(name='text')指定的字段名错误,富文本字段实际是content,配置必须匹配目标字段名才能生效:

修改admin/create.html和admin/edit.html的tail块:

{% block tail %}
  {{ super() }}
  {{ lib.form_js() }}
  {{ ckeditor.load() }}
  {{ ckeditor.config(name='content') }}  {# 将text改为content #}
{% endblock %}

2. 补充CKEditor上传处理路由

你已经配置了CKEDITOR_FILE_UPLOADER = 'main.upload',但缺少对应的视图函数处理上传请求。在main蓝图中添加以下代码:

from flask import Blueprint, request, url_for
from flask_ckeditor import upload_success, upload_fail
import os
from your_app import app  # 替换为你的Flask实例

main = Blueprint('main', __name__)

@main.route('/upload', methods=['POST'])
def upload():
    f = request.files.get('upload')
    # 校验文件扩展名
    extension = f.filename.split('.')[-1].lower()
    if extension not in app.config['ALLOWED_EXTENSIONS']:
        return upload_fail(message='不支持的文件类型')
    # 保存文件到指定目录
    save_path = os.path.join(app.config['UPLOADED_PATH'], f.filename)
    f.save(save_path)
    # 返回CKEditor要求的JSON响应
    file_url = url_for('static', filename=f'img/{f.filename}')
    return upload_success(url=file_url)

3. 显式配置CKEditor工具栏(推荐)

默认工具栏可能未包含图片上传按钮,可在配置类中添加自定义工具栏配置:

class Config:
    # 原有配置...
    CKEDITOR_CONFIGS = {
        'default': {
            'toolbar': [
                ['Bold', 'Italic', 'Underline'],
                ['Link', 'Unlink'],
                ['Image', 'Table'],
                ['Source', 'Undo', 'Redo']
            ],
            'height': 1000,
            'width': '100%'
        }
    }

或者直接使用完整工具栏:'toolbar': 'full'

4. 检查上传目录的权限与存在性

确保上传目录存在且Flask进程有读写权限,可在应用初始化时添加目录创建逻辑:

basedir = os.path.abspath(os.path.dirname(__file__))
UPLOADED_PATH = os.path.join(basedir, 'static/img')
if not os.path.exists(UPLOADED_PATH):
    os.makedirs(UPLOADED_PATH)

完成以上修改后重启应用,CKEditor的图片上传按钮会正常显示,且能完成图片上传流程。

内容的提问来源于stack exchange,提问作者Fadi Al-khatib

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:07:02