ASP.net core 使用UEditor.Core 實現 ueditor 上傳功能


ASP.net core 使用UEditor.Core 實現 ueditor 上傳功能

首先通過nuget 引用UEditor.Core,作者github:https://github.com/baiyunchen/UEditor.Core/

在Startup.cs中添加

services.AddUEditorService();   

 

引入ueditor並配置

從ueditor官網下載最新版本的壓縮包,並放到項目的wwwroot下面的lib文件夾中,然后在你需要的使用UEditor的頁面或全局引入ueditor.config.js和ueditor.all.min.js文件。

打開ueditor.config.js文件,將其中的serverUrl項改為UEditorController中Upload方法對應的地址(沒有改路由的話應該是:UEditor/Upload)。

配置靜態資源文件夾

            app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "upload")),
                    RequestPath = "/upload",
                    OnPrepareResponse = ctx =>
                    {
                        ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=36000");
                    }
                });
    

解決中文被html編碼的問題

            //解決中文被html編碼的問題
                services.Configure(options =>
                {
                    options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs);
                });
    

添加后端配置文件

將下載ueditor .net 中config.js 改名 為ueditor.json添加到項目根目錄。

ueditor.json

/* 前后端通信相關的配置,注釋只允許使用多行方式 */
    {
      /* 上傳圖片配置項 */
      "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */
      "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
      "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
      "imageAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 上傳圖片格式顯示 */
      "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
      "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
      "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
      "imageUrlPrefix": "/", /* 圖片訪問路徑前綴 */
      "imagePathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      /* {filename} 會替換成原文件名,配置這項需要注意中文亂碼問題 */
      /* {rand:6} 會替換成隨機數,后面的數字是隨機數的位數 */
      /* {time} 會替換成時間戳 */
      /* {yyyy} 會替換成四位年份 */
      /* {yy} 會替換成兩位年份 */
      /* {mm} 會替換成兩位月份 */
      /* {dd} 會替換成兩位日期 */
      /* {hh} 會替換成兩位小時 */
      /* {ii} 會替換成兩位分鍾 */
      /* {ss} 會替換成兩位秒 */
      /* 非法字符 \ : * ? " < > | */
      /* 具請體看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */
      /* 塗鴉圖片上傳配置項 */
      "scrawlActionName": "uploadscrawl", /* 執行上傳塗鴉的action名稱 */
      "scrawlFieldName": "upfile", /* 提交的圖片表單名稱 */
      "scrawlPathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      "scrawlMaxSize": 2048000, /* 上傳大小限制,單位B */
      "scrawlUrlPrefix": "/", /* 圖片訪問路徑前綴 */
      "scrawlInsertAlign": "none",
      /* 截圖工具上傳 */
      "snapscreenActionName": "uploadimage", /* 執行上傳截圖的action名稱 */
      "snapscreenPathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      "snapscreenUrlPrefix": "/", /* 圖片訪問路徑前綴 */
      "snapscreenInsertAlign": "none", /* 插入的圖片浮動方式 */
      /* 抓取遠程圖片配置 */
      "catcherLocalDomain": [ "127.0.0.1", "localhost", "img.baidu.com" ],
      "catcherActionName": "catchimage", /* 執行抓取遠程圖片的action名稱 */
      "catcherFieldName": "source", /* 提交的圖片列表表單名稱 */
      "catcherPathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      "catcherUrlPrefix": "/", /* 圖片訪問路徑前綴 */
      "catcherMaxSize": 2048000, /* 上傳大小限制,單位B */
      "catcherAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 抓取圖片格式顯示 */
      /* 上傳視頻配置 */
      "videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */
      "videoFieldName": "upfile", /* 提交的視頻表單名稱 */
      "videoPathFormat": "upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      "videoUrlPrefix": "/", /* 視頻訪問路徑前綴 */
      "videoMaxSize": 102400000, /* 上傳大小限制,單位B,默認100MB */
      "videoAllowFiles": [
        ".flv",
        ".swf",
        ".mkv",
        ".avi",
        ".rm",
        ".rmvb",
        ".mpeg",
        ".mpg",
        ".ogg",
        ".ogv",
        ".mov",
        ".wmv",
        ".mp4",
        ".webm",
        ".mp3",
        ".wav",
        ".mid"
      ], /* 上傳視頻格式顯示 */
      /* 上傳文件配置 */
      "fileActionName": "uploadfile", /* controller里,執行上傳視頻的action名稱 */
      "fileFieldName": "upfile", /* 提交的文件表單名稱 */
      "filePathFormat": "upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
      "fileUrlPrefix": "/", /* 文件訪問路徑前綴 */
      "fileMaxSize": 51200000, /* 上傳大小限制,單位B,默認50MB */
      "fileAllowFiles": [
        ".png",
        ".jpg",
        ".jpeg",
        ".gif",
        ".bmp",
        ".flv",
        ".swf",
        ".mkv",
        ".avi",
        ".rm",
        ".rmvb",
        ".mpeg",
        ".mpg",
        ".ogg",
        ".ogv",
        ".mov",
        ".wmv",
        ".mp4",
        ".webm",
        ".mp3",
        ".wav",
        ".mid",
        ".rar",
        ".zip",
        ".tar",
        ".gz",
        ".7z",
        ".bz2",
        ".cab",
        ".iso",
        ".doc",
        ".docx",
        ".xls",
        ".xlsx",
        ".ppt",
        ".pptx",
        ".pdf",
        ".txt",
        ".md",
        ".xml"
      ], /* 上傳文件格式顯示 */
      /* 列出指定目錄下的圖片 */
      "imageManagerActionName": "listimage", /* 執行圖片管理的action名稱 */
      "imageManagerListPath": "upload/image", /* 指定要列出圖片的目錄 */
      "imageManagerListSize": 20, /* 每次列出文件數量 */
      "imageManagerUrlPrefix": "/", /* 圖片訪問路徑前綴 */
      "imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
      "imageManagerAllowFiles": [ ".png", ".jpg", ".jpeg", ".gif", ".bmp" ], /* 列出的文件類型 */
      /* 列出指定目錄下的文件 */
      "fileManagerActionName": "listfile", /* 執行文件管理的action名稱 */
      "fileManagerListPath": "upload/file", /* 指定要列出文件的目錄 */
      "fileManagerUrlPrefix": "/", /* 文件訪問路徑前綴 */
      "fileManagerListSize": 20, /* 每次列出文件數量 */
      "fileManagerAllowFiles": [
        ".png",
        ".jpg",
        ".jpeg",
        ".gif",
        ".bmp",
        ".flv",
        ".swf",
        ".mkv",
        ".avi",
        ".rm",
        ".rmvb",
        ".mpeg",
        ".mpg",
        ".ogg",
        ".ogv",
        ".mov",
        ".wmv",
        ".mp4",
        ".webm",
        ".mp3",
        ".wav",
        ".mid",
        ".rar",
        ".zip",
        ".tar",
        ".gz",
        ".7z",
        ".bz2",
        ".cab",
        ".iso",
        ".doc",
        ".docx",
        ".xls",
        ".xlsx",
        ".ppt",
        ".pptx",
        ".pdf",
        ".txt",
        ".md",
        ".xml"
      ] /* 列出的文件類型 */
    }
    

如果想上傳到根目錄特定文件夾,只需要修改

"upload/file" / "upload/image/"類似字段即可

開始使用UEditor

 創建后端接口

 例如:

public class UEditorController : Controller
    {
        private readonly UEditorService _ueditorService;
        public UEditorController(UEditorService ueditorService)
        {
            this._ueditorService = ueditorService;
        }
    
        //如果是API,可以按MVC的方式特別指定一下API的URI
        [HttpGet, HttpPost]   
        public ContentResult Upload()
        {
            var response = _ueditorService.UploadAndGetResponse(HttpContext);
            return Content(response.Result, response.ContentType);
        }
    }
    

 如果想指定區域如下

using UEditor.Core;
    
    namespace Website.MVC.Areas.Admin.Controllers
    {
        [Area("Admin")]
        [Authorize]
        [IgnoreAntiforgeryToken]
        [Route("{area}/{controller}")]
        public class UploadController : Controller
        {
            private readonly UEditorService _uEditorService;
            public UploadController(UEditorService uEditorService)
            {
                _uEditorService = uEditorService;
            }
         
            [Route("UEditor")]
            [AllowAnonymous]
            [HttpGet, HttpPost]
            public ContentResult UEditor()
            {
                var response = _uEditorService.UploadAndGetResponse(HttpContext);
                return Content(response.Result, response.ContentType);
            }
        }
    }
    

 wwwroot/lib/ueditor-1.4.3.3/ueditor.config.js中需要設置controller

        // 服務器統一請求接口路徑
            //, serverUrl: "/ueditor/upload"
            , serverUrl: "/Admin/Upload/UEditor"
    

 在需要的.cshtml中添加引用

         ***
            <!--form 表單ID name 仍然可以使用-->
            <div class="layui-form-item">
                <script id="Content" name="Content" type="text/plain" style="width:1366px;height:500px;">
                </script>
            </div>
            ***
        <!-- 配置文件 -->
        <script src="~/lib/ueditor-1.4.3.3/ueditor.config.js" asp-append-version="true"></script>
        <!-- 編輯器源碼文件 -->
        <script src="~/lib/ueditor-1.4.3.3/ueditor.all.min.js" asp-append-version="true"></script>
        <!--建議手動加載語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
        <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
        <script type="text/javascript" charset="utf-8" src="~/lib/ueditor-1.4.3.3/lang/zh-cn/zh-cn.js">
    
    

 然后在頁面的最后添加如下JS代碼:

<script type="text/javascript">
        var ue = UE.getEditor('container', {
            initialFrameHeight: 500
        });
    </script>

 如果使用layui 如下:

//layer 彈窗索引
    var layerindex;
    var ueditContentIndex;
    layui.use(['layer', 'table', 'upload', 'laydate', 'form'], function () {
        var table = layui.table,
            layer = layui.layer,
            form = layui.form,
            laydate = layui.laydate,
            upload = layui.upload;
            var useUEditor = function () {
            //建立編輯器
            ueditContentIndex = UE.getEditor('ArticleContent', {
                initialFrameHeight: 500
            });
    
            ****
    
                    if (ueditContentIndex != null) {
                        ueditContentIndex.destroy();
                    }
    
                    useUEditor();       //實例化編輯器,只能放在layer 彈窗后
                    // editor准備好之后才可以使用
                    ueditContentIndex.addListener("ready", function () {
                        //賦值
                        ueditContentIndex.setContent(""); //你想要的值 
                    });
            }
    
            ****
            ajax:
            $.ajax({
                type: 'post',
                url: "/Admin/Article/SubmitArticle",//請求的action路徑
                data: {
                    ****
                    ArticleContent: formdata.Content, //UEditor name 直接用layui formdata 省事
                    *****
                },
                dataType: "json",
                success: function (data) {
                    console.log(data);
                },
                error: function (data) {
                    console.log(data);
                    layer.msg('提交失敗!', { icon: 2 });
                }
            });   
    });
    

 最后修復UEditor  會“吃掉” 'class', 'style' 的bug.

在 /wwwroot/lib/ueditor-1.4.3.3/ueditor.config.js 第366行

設置所有便簽都加上['class', 'style'],(有xss風險慎用)

		// xss過濾白名單 名單來源: https://raw.githubusercontent.com/leizongmin/js-xss/master/lib/default.js
            ,whitList: {
                a:      ['target', 'href', 'title', 'class', 'style'],
                abbr:   ['title', 'class', 'style'],
                address: ['class', 'style'],
                area:   ['shape', 'coords', 'href', 'alt'],
                article: ['class', 'style'],
                aside: ['class', 'style'],
                audio:  ['autoplay', 'controls', 'loop', 'preload', 'src', 'class', 'style'],
                b:      ['class', 'style'],
                bdi:    ['dir'],
                bdo:    ['dir'],
                big: ['class', 'style'],
                blockquote: ['cite', 'class', 'style'],
                br: ['class', 'style'],
                caption: ['class', 'style'],
                center: ['class', 'style'],
                cite: ['class', 'style'],
                code:   ['class', 'style'],
                col:    ['align', 'valign', 'span', 'width', 'class', 'style'],
                colgroup: ['align', 'valign', 'span', 'width', 'class', 'style'],
                dd:     ['class', 'style'],
                del:    ['datetime'],
                details: ['open'],
                div:    ['class', 'style'],
                dl:     ['class', 'style'],
                dt:     ['class', 'style'],
                em:     ['class', 'style'],
                font:   ['color', 'size', 'face'],
                footer: ['class', 'style'],
                h1:     ['class', 'style'],
                h2:     ['class', 'style'],
                h3:     ['class', 'style'],
                h4:     ['class', 'style'],
                h5:     ['class', 'style'],
                h6:     ['class', 'style'],
                header: ['class', 'style'],
                hr: ['class', 'style'],
                i:      ['class', 'style'],
                img: ['src', 'alt', 'title', 'width', 'height', 'id', '_src', 'loadingclass', 'class', 'data-latex','style'],
                ins:    ['datetime'],
                li:     ['class', 'style'],
                mark: ['class', 'style'],
                nav: ['class', 'style'],
                ol:     ['class', 'style'],
                p:      ['class', 'style'],
                pre:    ['class', 'style'],
                s:      ['class', 'style'],
                section: ['class', 'style'],
                small: ['class', 'style'],
                span:   ['class', 'style'],
                sub:    ['class', 'style'],
                sup:    ['class', 'style'],
                strong: ['class', 'style'],
                table:  ['width', 'border', 'align', 'valign', 'class', 'style'],
                tbody:  ['align', 'valign', 'class', 'style'],
                td:     ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                tfoot:  ['align', 'valign', 'class', 'style'],
                th:     ['width', 'rowspan', 'colspan', 'align', 'valign', 'class', 'style'],
                thead:  ['align', 'valign', 'class', 'style'],
                tr:     ['rowspan', 'align', 'valign', 'class', 'style'],
                tt: ['class', 'style'],
                u: ['class', 'style'],
                ul:     ['class', 'style'],
                video:  ['autoplay', 'controls', 'loop', 'preload', 'src', 'height', 'width', 'class', 'style']
            }
        };
    

 UEditor.Core作者github地址: https://github.com/baiyunchen/UEditor.Core

 pass:我會經常修改 不希望被轉載!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM