CKEditor 是廣受歡迎的 Web 富文本編輯器,搭配 CKFinder 即可實現圖片/檔案上傳與管理。本文記錄在 ASP.NET WebForms 專案中完整整合兩者的步驟,包含套件引用、控制項註冊、伺服端整合與權限配置。
samples 資料夾,將 ckeditor、ckfinder 兩資料夾複製至專案根目錄。bin/Release 下的組件:CKEditor.NET.dll、CKFinder.dll。在需使用編輯器的 .aspx 頁面頂端註冊標籤前綴:
<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
於表單中放置控制項:
<CKEditor:CKEditorControl ID="txtNewsContent" runat="server" />
在代碼後置 OnLoad 中建立 FileBrowser 並關聯編輯器,同時設定上傳儲存路徑:
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
var browser = new CKFinder.FileBrowser();
browser.SetupCKEditor(txtNewsContent);
browser.BasePath = "~/Files/"; // 上傳檔案實體儲存資料夾
}
編輯 ckfinder/config.ascx:
CheckAuthentication() 預設回傳 false,需改為驗證使用者登入狀態:public override bool CheckAuthentication() {
// 範例:僅允許已登入使用者上傳
return HttpContext.Current.Session["UserId"] != null;
}
SetConfig() 中限制副檔名、檔案大小、資料夾權限:config.AllowedExtensions = new Dictionary<string, string[]> {
["Images"] = new[] { "jpg", "jpeg", "png", "gif", "bmp" },
["Documents"] = new[] { "pdf", "doc", "docx", "xls", "xlsx" }
};
config.DisallowedExtensions = new[] { "php", "asp", "aspx", "exe", "dll" };
config.MaxFileSize = 10 * 1024 * 1024; // 10 MB
config.ResourceAcl = new AccessControlRules {
{ Role.Everyone, ResourceType.All, Folder.All, AccessControlRules.Permission.Read },
{ Role.Authenticated, ResourceType.All, Folder.All, AccessControlRules.Permission.Read | AccessControlRules.Permission.Write }
};
編輯 ckeditor/config.js 調整工具列群組、移除多餘按鈕、設定語系等:
CKEDITOR.editorConfig = function(config) {
config.language = 'zh-tw';
config.toolbarGroups = [
{ name: 'document', groups: ['mode', 'document', 'doctools'] },
{ name: 'clipboard', groups: ['clipboard', 'undo'] },
{ name: 'editing', groups: ['find', 'selection', 'spellchecker', 'editing'] },
{ name: 'forms', groups: ['forms'] },
'/',
{ name: 'basicstyles', groups: ['basicstyles', 'cleanup'] },
{ name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align', 'bidi', 'paragraph'] },
{ name: 'links', groups: ['links'] },
{ name: 'insert', groups: ['insert'] },
'/',
{ name: 'styles', groups: ['styles'] },
{ name: 'colors', groups: ['colors'] },
{ name: 'tools', groups: ['tools'] }
];
config.removeButtons = 'Save,NewPage,Preview,Print,Templates,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,Flash,Iframe,About';
};
BasePath 路徑正確、IIS 已啟用靜態內容處理、web.config 未封鎖 .ashx 處理常式。CheckAuthentication 邏輯、資料夾寫入權限(IIS_IUSRS)。ckeditor/ckeditor.js 可正常載入、無 JS 錯誤阻塞初始化。完成上述設定,即可在 ASP.NET 專案中擁有功能完整、安全可控的富文本編輯環境。