Asp.Net Core MVC 中富文本编辑器CKEditor 5的配置及使用
有时我们需要使用宣文本编辑器来上传图片,编辑文本等内容。我使用的是CKEditor 5,可以直接兼容vue2和vue3,我的开发环境是H5端,框架使用的是Element UI
在此要说明一点,ckeditor5在ie11下是不兼容的,要想在ie11下正常运行,可能需要较低版本的ckeditor,在解决兼容性的时候,发现ckeditor4是兼容ie11的
vue中的使用说明:
https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/frameworks/vuejs-v2.html
https://ckeditor.com/docs/ckeditor5/latest/installation/getting-started/frameworks/vuejs-v3.html
读写数据:
https://ckeditor.com/docs/ckeditor5/latest/installation/advanced/saving-data.html
第一步:根据需求定制生成CKEditor
地址:https://ckeditor.com/ckeditor-5/online-builder/
根据自己的需求选择插件,配置好后根据步骤完成后,下载到本地。
然后将文件夹build中的ckeditor.js引入到页面中
第二步页面配置:
引入js文件
配置:
ckfinder用于配置上传文件的请求路径
文件上传配置说明文档:https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/ckfinder.html
返回JSON示例:
{"fileName":"ba24cb71398849d398330c23b2cceb9a.jpg","uploaded":1,"url":"/uploads/20220521/ba24cb71398849d398330c23b2cceb9a.jpg"
第三步:服务端上传设置
[HttpPost] [Route("api/upload")] [AllowAnonymous] public async TaskUploadFileAsync(IFormFile upload) { string dateFile = DateTime.Now.ToString("yyyyMMdd"); // 如:保存到网站根目录下的 uploads 目录 var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, $"wwwroot/uploads/{dateFile}"); if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath); //// 这里还可以获取文件的信息 // var size = file.Length / 1024.0; // 文件大小 KB // var clientFileName = file.FileName; // 客户端上传的文件名 // var contentType = file.ContentType; // 获取文件 ContentType 或解析 MIME 类型 // 避免文件名重复,采用 GUID 生成 var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(upload.FileName); var filePath = Path.Combine(savePath, fileName); // 保存到指定路径 using (var stream = System.IO.File.Create(filePath)) { await upload.CopyToAsync(stream); } // 在动态 API 直接返回对象即可,无需 OK 和 IActionResult return Ok(new { fileName=fileName, uploaded=1, url=$"/uploads/{dateFile}/"+fileName }); }
最终效果: