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

如何用PHP+MySQL通过CKEditor5行内编辑器上传图片并保存路径

解决CKEditor5行内编辑器图片上传及报错问题

一、修复"Uncaught ReferenceError: CKEDITOR is not defined"错误

你代码里的CKEDITOR.replace()是CKEditor4专属API,CKEditor5没有全局的CKEDITOR对象,直接删除这段脚本即可。

二、配置CKEditor5图片上传功能

修改InlineEditor的初始化配置,添加图片上传相关参数,指定上传接口地址:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CKEditor 5 – Inline editor</title>
    <script src="http://localhost/cmm/dev2/ckeditor5-build-inline-31.1.0/ckeditor.js"></script>
</head>
<body>
    <h2>Classic CKEditor5</h2>
    
    <div id="editor">
        <textarea>Inline CKEditor Working Fine</textarea>
    </div>
    <!-- 新增提交按钮用于保存内容 -->
    <button id="saveBtn">保存内容</button>
   
    <script>
        let editorInstance; // 保存编辑器实例,方便后续获取内容
        InlineEditor
            .create( document.querySelector( '#editor' ),{
                 toolbar: {
                    items: [
                        'heading', '|',
                        'fontfamily', 'fontsize', '|',
                        'alignment', '|',
                        'fontColor', 'fontBackgroundColor', '|',
                        'bold', 'italic', 'strikethrough', 'underline',  '|',
                        'link', '|',
                        'outdent', 'indent', '|',
                        'bulletedList', 'numberedList', '|',
                        'insertTable', '|',
                        'uploadImage', 'blockQuote', '|',
                        'undo', 'redo'
                    ],
                    shouldNotGroupWhenFull: true
                },
                heading: {
                    options: [
                        { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                        { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
                        { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }
                    ]
                },
                // 新增图片上传配置
                image: {
                    upload: {
                        url: 'upload.php', // 指向PHP上传脚本
                        headers: {
                            // 若需验证可添加请求头,比如CSRF令牌
                            // 'X-CSRF-TOKEN': 'your-token'
                        }
                    }
                }
            } )
            .then(editor => {
                editorInstance = editor; // 保存实例用于后续获取内容
            })
            .catch( error => {
                console.error( error );
            });

        // AJAX提交编辑器内容到数据库
        document.getElementById('saveBtn').addEventListener('click', function() {
            const content = editorInstance.getData(); // 获取编辑器HTML内容
            fetch('save_content.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `content=${encodeURIComponent(content)}`
            })
            .then(response => response.json())
            .then(data => {
                alert(data.success ? '保存成功' : '保存失败');
            })
            .catch(error => {
                console.error('保存出错:', error);
            });
        });
    </script>
</body>
</html>

三、编写PHP上传脚本(upload.php)

该脚本负责接收上传图片、验证类型、保存到服务器,并返回CKEditor5要求的JSON响应:

<?php
// 定义上传目录(确保目录有写入权限)
$uploadDir = 'uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// 允许的图片类型
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

// 处理上传请求
if (isset($_FILES['upload'])) {
    $file = $_FILES['upload'];
    $fileName = uniqid() . '_' . basename($file['name']);
    $filePath = $uploadDir . $fileName;

    // 验证文件类型
    if (in_array($file['type'], $allowedTypes)) {
        if (move_uploaded_file($file['tmp_name'], $filePath)) {
            // 返回CKEditor5需要的JSON格式
            echo json_encode([
                'uploaded' => true,
                'url' => 'http://localhost/cmm/dev2/' . $filePath // 图片的完整访问URL
            ]);
            exit;
        } else {
            echo json_encode([
                'uploaded' => false,
                'error' => ['message' => '文件保存失败']
            ]);
            exit;
        }
    } else {
        echo json_encode([
            'uploaded' => false,
            'error' => ['message' => '仅允许上传JPG、PNG、GIF格式图片']
        ]);
        exit;
    }
} else {
    echo json_encode([
        'uploaded' => false,
        'error' => ['message' => '未检测到上传文件']
    ]);
    exit;
}
?>

四、编写保存内容到数据库的PHP脚本(save_content.php)

该脚本接收AJAX发送的内容,存入数据库:

<?php
// 连接数据库(替换为你的实际配置)
$servername = 'localhost';
$username = 'your_db_user';
$password = 'your_db_pass';
$dbname = 'your_db_name';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'message' => '数据库连接失败']));
}

$content = isset($_POST['content']) ? $_POST['content'] : '';
if (!empty($content)) {
    // 预处理语句防止SQL注入
    $stmt = $conn->prepare("INSERT INTO your_table_name (content) VALUES (?)");
    $stmt->bind_param("s", $content);
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => '保存失败']);
    }
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => '内容不能为空']);
}
$conn->close();
?>

注意事项

  • 确保uploads/目录有写入权限(Linux下可执行chmod 755 uploads)。
  • 图片访问URL需根据你的实际项目路径修改,确保前端能正常访问。
  • 数据库部分请替换为你的实际数据库配置和表结构。

内容的提问来源于stack exchange,提问作者Revathi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:35:34