在.NET Framework中使用UEditor時,只需要將UEditor提供的后端服務,部署為一個子程序,即可直接使用文件上傳相關的服務,但是UEditor官方並未提供.Net Core的項目,並且.NET Core項目很多時候是跑在Linux上面的,也沒有子程序一說。
為了解決這個問題,我開發了一個.NET Core版本的后端服務,他已經在Github上開源https://github.com/baiyunchen/UEditor.Core,並提供了比較優質的中文文檔供大家參考。
大家可以參考Github中的文檔和源碼,以下內容時從Github中Copy而來:
建議別往下看了,直接去看Github中的內容!覺得有用的,請在Github上留下你的Star
安裝
建議從從nuget安裝
方式1:可以直接在Nuget中搜索UEditor.Core並安裝
方式2:通過命令行安裝
Install-Package UEditor.Core
配置
並在Startup.cs中的ConfigureServices方法中,加入以下代碼:
services.AddUEditorService("ueditor.json",true);
由於.Net Core默認只會從wwwroot目錄加載靜態文件,其他文件夾的靜態文件無法正常訪問。而我們希望將圖片上傳到網站根目錄的upload文件夾下,所以需要額外在Startup.cs
類的Configure方法中,增加如下代碼:
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");
}
});
然后在項目的根目錄,創建upload
文件夾(這里不創建會報錯)。
接下來,我們需要將ueditor后端的config.js
改名 為ueditor.json
添加到項目根目錄。
這里的配置文件可以在ueditor的下載包中,net文件夾下面找到,目前版本的具體路徑如下:
ueditor1_4_3_3-utf8-net\utf8-net\net\config.json
如果你懶得下載,也可以在本項目GitHub的Sample.Web下面找到ueditor.json
文件,然后粘貼到你項目的根目錄下。
如果你是從UEditor的下載包中復制的該文件,需要全局將該文件中的/ueditor/net/
替換為/
創建后端接口
創建一個UEditorController,並添加如下代碼:
public class UEditorController : Controller { private readonly UEditorService _ueditorService; public UEditorController(UEditorService ueditorService) { this._ueditorService = ueditorService; } [HttpGet, HttpPost] public ContentResult Upload() { var response = _ueditorService.UploadAndGetResponse(HttpContext); return Content(response.Result, response.ContentType); } }
引入ueditor並配置
從ueditor官網下載最新版本的壓縮包,並放到項目的wwwroot下面的lib文件夾中,然后在你需要的使用UEditor的頁面或全局引入ueditor.config.js
和ueditor.all.min.js
文件。
打開ueditor.config.js
文件,將其中的serverUrl
項改為:/ueditor/upload
。
開始使用UEditor
這部分如果遇到問題,請參考UEditor的官方文檔http://fex.baidu.com/ueditor/。
在你需要使用UEditor的HTML代碼中,添加如下代碼:
<script id="container" name="content" type="text/plain">
歡迎使用Ueditor.Core
</script>
然后在頁面的最后添加如下JS代碼:
<script type="text/javascript">
var ue = UE.getEditor('container', {
initialFrameHeight: 500
});
</script>