萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 整合百度 UEditor 富文本編輯器:從下載到前後端完整串接

UEditor 在 ASP.NET (Web Forms / MVC) 完整接入流程

百度 UEditor 為開源富文本編輯器,支援圖片/檔案/視頻上傳、代碼高亮、公式、圖表等。需 .NET Framework 4.0+。

1. 專案結構整理

Project/
├── ueditor/                    # 解壓官方 net 版本
│   ├── net/
│   │   ├── controller.ashx     # 核心處理器 (上傳、列圖、抓遠程)
│   │   ├── config.json         # 所有上傳路徑、大小、類型設定
│   │   └── App_Code/           # C# 原始碼 (複製到專案 App_Code)
│   ├── dialogs/                # 對話框頁面
│   ├── lang/zh-cn/zh-cn.js     # 中文語言包
│   ├── themes/default/         # 樣式主題
│   └── third-party/            # 第三方插件 (代碼高亮、截圖)
├── Scripts/UEditorHelper.js    # 封裝常用 API、預設配置
└── 頁面引用...

2. 關鍵設定:config.json

{
  "imageActionName": "uploadimage",
  "imageFieldName": "upfile",
  "imageMaxSize": 2048000,
  "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],
  "imagePathFormat": "/ueditor/net/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
  
  "scrawlActionName": "uploadscrawl",
  "scrawlPathFormat": "/ueditor/net/upload/scrawl/{yyyy}{mm}{dd}/{time}{rand:6}",
  
  "catcherActionName": "catchimage",
  "catcherPathFormat": "/ueditor/net/upload/catcher/{yyyy}{mm}{dd}/{time}{rand:6}",
  
  "videoActionName": "uploadvideo",
  "videoPathFormat": "/ueditor/net/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",
  
  "fileActionName": "uploadfile",
  "filePathFormat": "/ueditor/net/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",
  
  "imageManagerActionName": "listimage",
  "imageManagerListPath": "/ueditor/net/upload/image/",
  "fileManagerActionName": "listfile",
  "fileManagerListPath": "/ueditor/net/upload/file/"
}
  • `{yyyy}{mm}{dd}`:日期資料夾自動建立。
  • `{time}{rand:6}`:時間戳+6位隨機數,避免衝突。
  • 需給 `upload` 資料夾 **IIS_IUSRS 寫入權限**。

3. 頁面引用與初始化

<!-- 引用順序重要 -->
<script src="/ueditor/ueditor.config.js"></script>
<script src="/ueditor/ueditor.all.min.js"></script>
<script src="/ueditor/lang/zh-cn/zh-cn.js"></script>
<script src="/Scripts/UEditorHelper.js"></script>

<!-- 編輯器容器 -->
<script id="editor" type="text/plain" style="width:100%;height:400px;"></script>

<script>
var ue = UE.getEditor('editor', {
    autoHeightEnabled: false,  // 固定高度
    initialFrameHeight: 400,
    toolbars: [[ 'fullscreen', 'source', '|', 'bold', 'italic', 'underline', '|',
                 'forecolor', 'backcolor', '|', 'insertimage', 'insertvideo', 'attachment']]
});
</script>

4. UEditorHelper.js 封裝常用操作

// 取得純文字
function getText() {
    var range = UE.getEditor('editor').selection.getRange();
    range.select();
    return UE.getEditor('editor').selection.getText();
}

// 設定內容 (isAppendTo: true=追加, false=替換)
function setContent(html, isAppendTo) {
    UE.getEditor('editor').setContent(html, isAppendTo);
}

// 取得完整 HTML (含樣式)
function getAllHtml() { return UE.getEditor('editor').getAllHtml(); }

// 取得內容 HTML (供存資料庫)
function getContent() { return UE.getEditor('editor').getContent(); }

// 取得純文字 (供摘要)
function getContentTxt() { return UE.getEditor('editor').getContentTxt(); }

// 銷毀編輯器 (釋放記憶體)
function destroyEditor() { UE.getEditor('editor').destroy(); }

// 插入 HTML
function insertHtml(html) { UE.getEditor('editor').execCommand('insertHtml', html); }

5. 編輯現有資料:AJAX 載入內容

// 頁面載入時
$.post('/Handler/GetNews.ashx', { id: newsId }, function(data) {
    // data = { title: "...", content: "..." }
    $('#txtTitle').val(data.title);
    setContent(data.content, false);  // 替換編輯器內容
});

6. 伺服端儲存內容

// WebForms .aspx.cs
protected void BtnSave_Click(object sender, EventArgs e)
{
    string content = Request.Form["editor"];  // UEditor 隱藏 textarea name="editor"
    // 或 Request["editor"]
    SaveToDb(newsId, content);
}

// MVC Controller
[HttpPost, ValidateInput(false)]  // 允許 HTML 內容
public ActionResult Save(int id, string editor)
{
    _service.UpdateContent(id, editor);
    return Json(new { success = true });
}

7. 常見坑點與解決

問題原因解決
上傳圖片返回錯誤config.json 路徑錯誤、資料夾無寫入權限、controller.ashx 未註冊檢查 F12 Network 回應、給予 IIS_IUSRS 權限、web.config `` 註冊 .ashx
語言顯示英文未引用 zh-cn.js 或自動偵測失敗強制引用 `lang/zh-cn/zh-cn.js` 或配置 `UE.getEditor('editor', {lang:'zh-cn'})`
代碼高亮不工作SyntaxHighlighter 樣式/JS 未載入確認 third-party/SyntaxHighlighter 引用正確
內容無法儲存 (Request Validation)ASP.NET 預設攔截 HTML頁面 `<%@ Page ValidateRequest="false" %>` 或 MVC `[ValidateInput(false)]`
MVC 區域 (Area) 路徑錯誤UEditor 相對路徑基於網站根目錄config.json 使用絕對虛擬路徑 `/ueditor/...`,或動態注入 `serverUrl`

8. 現代替代方案

  • wangEditor:輕量、TypeScript、支援 Vue/React、MIT 授權。
  • Tiptap:Headless、基於 ProseMirror、高度可擴展。
  • Quill:模組化、輕量、社群活躍。
  • CKEditor 5:企業級、協同編輯、GPG 授權 (需付費商用)。

注意: UEditor 官方已多年不更新,存在 XSS、上傳驗證繞過等安全風險。生產環境**務必**加上傳檔案類型白名單、大小限制、病毒掃描、輸出端 XSS 過濾 (HTML Sanitizer)。新專案建議選用現代編輯器。

copyright © 萬盛學電腦網 all rights reserved