首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

.NET 環境下為百度 UEditor 編輯器新增圖片刪除功能完整教學

     編輯:ASP.NET 基礎

百度 UEditor 是一套功能強大的富文本編輯器,但版本迭代時常移除舊有功能,且舊版代碼難以直接複用,讓開發者頗感困擾。筆者近期升級至 1.2.5 版本後發現,原本內建的「圖片管理」中刪除圖片功能竟被移除。經過一番鑽研與修改,成功將該功能加回,現整理完整實作步驟供參考。

一、 修改伺服器端處理程式 (imageManager.ashx)

首先需擴充 ueditor/net/imageManager.ashx,新增處理 action=del 的邏輯,實現實體檔案刪除。

核心代碼邏輯

  • 接收前端傳來的 fileName 參數。
  • 遍歷設定的圖片儲存目錄(預設為 upload、upload1)。
  • 比對檔名,找到後呼叫 File.Delete 刪除實體檔案。
  • 返回 success 或 error 供前端判斷。
<%@ WebHandler Language="C#" Class="imageManager" %>
using System;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;

public class imageManager : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";

        // 圖片儲存目錄列表,建議使用縮略圖路徑以提升載入速度
        string[] paths = { "upload", "upload1" };
        string[] filetype = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };

        string action = context.Server.HtmlEncode(context.Request["action"]);

        // 1. 獲取圖片列表 (原有邏輯)
        if (action == "get")
        {
            String str = String.Empty;
            foreach (string path in paths)
            {
                DirectoryInfo info = new DirectoryInfo(context.Server.MapPath(path));
                if (info.Exists)
                {
                    DirectoryInfo[] infoArr = info.GetDirectories();
                    foreach (DirectoryInfo tmpInfo in infoArr)
                    {
                        foreach (FileInfo fi in tmpInfo.GetFiles())
                        {
                            if (Array.IndexOf(filetype, fi.Extension) != -1)
                            {
                                str += path + "/" + tmpInfo.Name + "/" + fi.Name + "ue_separate_ue";
                            }
                        }
                    }
                }
            }
            context.Response.Write(str);
        }

        // 2. 【新增】刪除圖片功能
        if (action == "del")
        {
            string fileName = context.Server.HtmlEncode(context.Request["fileName"]);
            bool isDeleted = false;

            try
            {
                foreach (string path in paths)
                {
                    string physicalPath = context.Server.MapPath(path);
                    DirectoryInfo info = new DirectoryInfo(physicalPath);
                    if (info.Exists)
                    {
                        // 遍歷日期命名的子目錄 (如 2023-10-25)
                        foreach (DirectoryInfo tmpInfo in info.GetDirectories())
                        {
                            foreach (FileInfo fi in tmpInfo.GetFiles())
                            {
                                // 確認為允許的圖片類型並檔名匹配
                                if (Array.IndexOf(filetype, fi.Extension) != -1 && fi.Name.Equals(fileName))
                                {
                                    string fullPath = physicalPath + "/" + tmpInfo.Name + "/" + fileName;
                                    File.Delete(fullPath);
                                    isDeleted = true;
                                    break;
                                }
                            }
                            if (isDeleted) break;
                        }
                    }
                    if (isDeleted) break;
                }
                context.Response.Write(isDeleted ? "success" : "error");
            }
            catch
            {
                context.Response.Write("error");
            }
        }
    }

    public bool IsReusable { get { return false; } }
}

二、 修改前端圖片管理邏輯 (image.js)

接著修改 ueditor/dialogs/image/image.js,在「線上圖片/圖片管理」Tab 切換時,為每張圖片綁定雙擊刪除事件,並透過 AJAX 呼叫後端刪除 API。

關鍵修改點

  1. 在 clickHandler 函式中,切換至 imgManager Tab 時,初始化圖片列表。
  2. 為動態生成的 <img> 元素新增 ondblclick 事件。
  3. 彈出確認對話框,防止誤操作。
  4. 呼叫 ajax.request 發送 action=del 請求。
  5. 刪除成功後,移除對應的 DOM 節點;失敗則提示錯誤。
// 在 clickHandler 函式內部,id == "imgManager" 的判斷區塊中新增 ondblclick 邏輯:

if (id == "imgManager") {
    list.style.display = "";
    // 已初始化過則不再重複請求
    if (!list.children.length) {
        ajax.request(editor.options.imageManagerUrl, {
            timeout: 100000,
            action: "get",
            onsuccess: function (xhr) {
                var tmp = utils.trim(xhr.responseText),
                    imageUrls = !tmp ? [] : tmp.split("ue_separate_ue"),
                    length = imageUrls.length;

                g("imageList").innerHTML = !length ? "  " + lang.noUploadImage : "";

                for (var k = 0, ci; ci = imageUrls[k++];) {
                    var img = document.createElement("img");
                    var div = document.createElement("div");
                    div.appendChild(img);
                    div.style.display = "none";
                    g("imageList").appendChild(div);

                    img.onclick = function () {
                        changeSelected(this);
                    };

                    // 【新增】雙擊刪除圖片
                    img.ondblclick = function () {
                        var me = this,
                            src = me.getAttribute("src", 2);
                        // 確認對話框
                        if (!confirm("刪除操作不可恢復,您確認要刪除本圖片嗎?")) return;

                        // 呼叫後端刪除 API
                        ajax.request(editor.options.imageManagerUrl, {
                            action: "del",
                            // 從 URL 中解析純檔名
                            fileName: src.substr(src.lastIndexOf("/") + 1),
                            onsuccess: function (xhr) {
                                if (xhr.responseText == "success") {
                                    // 從 DOM 移除
                                    me.parentNode.removeChild(me);
                                } else {
                                    alert("伺服器刪除圖片失敗,請重試!");
                                }
                            },
                            onerror: function () {
                                alert("網路請求異常,刪除失敗。");
                            }
                        });
                    };

                    img.onload = function () {
                        this.parentNode.style.display = "";
                        var w = this.width, h = this.height;
                        scale(this, 100, 120, 80);
                        this.title = lang.toggleSelect + w + "X" + h;
                        this.onload = null;
                    };

                    // 設定圖片來源 (支援延遲載入)
                    img.setAttribute(k < 35 ? "src" : "lazy_src", editor.options.imageManagerPath + ci.replace(/\s+|\s+/ig, ""));
                    img.setAttribute("data_ue_src", editor.options.imageManagerPath + ci.replace(/\s+|\s+/ig, ""));
                }
            },
            onerror: function () {
                g("imageList").innerHTML = lang.imageLoadError;
            }
        });
    }
}

三、 功能驗證與注意事項

測試步驟

  1. 部署修改後的 imageManager.ashx 至伺服器。
  2. 清除瀏覽器快取,重新載入編輯器頁面。
  3. 點擊編輯器工具列「插入圖片」圖示,切換至「圖片管理」Tab。
  4. 雙擊任一已上傳圖片,確認彈出提示框並點擊「確定」。
  5. 觀察圖片是否從列表消失,並至伺服器檔案系統確認實體檔案已刪除。

常見問題排查

  • 權限不足:確保 IIS 應用程式池身分拥有 upload 目錄的寫入/修改權限(刪除需要寫入權限)。
  • 路徑解析錯誤:若圖片儲存路徑非預設結構,需同步調整 C# 端遍歷邏輯與 JS 端 fileName 解析邏輯。
  • 快取導致列表未更新:AJAX 請求已設 timeout,若仍有舊資料,可在請求 URL 附加時間戳參數強制刷新。

結語

透過擴充伺服器端 imageManager.ashx 與前端 image.js,我們成功為 UEditor 1.2.5+ 版本補回了「圖片管理中刪除圖片」的實用功能。此修改採用雙擊觸發搭配確認機制,兼顧操作效率與資料安全。希望這份教學能幫助同樣遇到此問題的 .NET 開發者快速解決困擾。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved