ASP.net core 使用UEditor.Core 实现 ueditor 上传功能

时间:2023-03-08 18:04:21

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:我会经常修改 不希望被转载!