KindEditor 是經典富文本編輯器,ThinkPHP 擴展類 Keditor 封裝了 JS 生成、圖片上傳、遠程圖片瀏覽、圖片刪除等功能。本文整理安裝到進階用法全流程。
Keditor.class.php、JSON.class.php 複製至 ThinkPHP/Lib/ORG/Net/editor/ 資料夾 (KindEditor 官方完整包) 複製至專案 Public/editor/ (與 index.php 同級)。在 Public/ 下建立 Upload/ 目錄存放上傳圖片KeditorAction.class.php 複製至專案 Lib/Action/,內含 upload()、filemanager() 方法<?php
public function edit() {
import('ORG.Net.Keditor');
$ke = new Keditor();
$ke->id = 'content'; // 對應 textarea id
$keshow = $ke->show(); // 生成 JS 初始化代碼
$this->assign('keshow', $keshow);
$this->display();
}
?>
<html>
<head>
{$keshow} {# 建議放在 head,輸出 KindEditor JS + 初始化腳本 #}
</head>
<body>
<form method="post" action="__URL__/save">
<textarea id="content" name="content" style="width:700px;height:400px;"></textarea>
<input type="submit" value="提交">
</form>
</body>
</html>
| 屬性 | 說明 | 預設值 |
|---|---|---|
jspath | KindEditor 核心 JS 路徑 | /Public/editor/kindeditor.js |
form | 表單 ID (配合 Ctrl+Enter 提交) | form1 |
imgid | 隱藏域 ID,存放上傳圖片 URL (逗號分隔),便於刪除同步清理 | img |
| 屬性 | 說明 | 範例 |
|---|---|---|
items | 工具欄按鈕陣列 | "['source','|','fullscreen','undo','redo','print','cut','copy','paste']" |
afterCreate | 編輯器建立後回調 | "function(id){alert('ready:'+id)}" |
resizeMode | 拖曳調整模式 | 2 (寬高), 1 (僅高), 0 (禁用) |
allowFileManager | 啟用遠程圖片瀏覽 | true / false |
imageUploadJson | 上傳接口 URL | /index.php/Keditor/upload |
fileManagerJson | 圖片瀏覽接口 URL | /index.php/Keditor/filemanager |
$ke->items = 'little' — 精簡模式工具欄$ke->afterCreate = 'ctrlenter' — 啟用 Ctrl+Enter 提交表單 (需同時設 $ke->form = 'your_form_id')數字/布林屬性 不要加引號:$ke->resizeMode = 2; (正確),$ke->resizeMode = "2"; (錯誤)。字串/陣列/函數需加引號。
import('ORG.Net.Keditor');
Keditor::upload(
'./Public/Upload/', // 儲存目錄 (相對 index.php)
'/Public/Upload/', // 訪問 URL 前綴 (絕對路徑)
array('gif','jpg','jpeg','png','bmp'), // 允許類型
1000000 // 最大尺寸 (Bytes, 此處 1MB)
);
Keditor::filemanager(
'./Public/Upload/',
'/Public/Upload/',
array('gif','jpg','jpeg','png','bmp')
);
// 刪除文章時同步清理圖片
Keditor::delimg($article['img_field']); // 傳入存放圖片 URL 的字段值 (逗號分隔)
$ke->show('{id:"content", width:"700px", height:"300px", imgid:"img"}');
// 注意:此方式無法設定 jspath、form、little、ctrlenter 等擴展屬性
在 KeditorAction.class.php 的 upload()、filemanager() 方法開頭添加:
// 僅允許管理員
if (!session('?admin')) {
echo json_encode(array('error' => 1, 'message' => '無權限'));
exit;
}
savePath 需相對 index.php,確認 Public/Upload/ 存在且可寫mbstring 設定imageUploadJson 返回的 url 是否為正確的絕對路徑 /Public/Upload/xxx.jpg