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文件
1 | <script type= "text/javascript" src= "/js/ckeditor.js" ></script> |
配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <script type= "text/javascript" > ClassicEditor .create(document.querySelector( '#editor' ), { // toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ] ckfinder: { // Upload the images to the server using the CKFinder QuickUpload command. uploadUrl: '/api/upload' , // Define the CKFinder configuration (if necessary). options: { resourceType: 'Images' } } }) .then(editor => { window.editor = editor; }) . catch (err => { console.error(err.stack); }); </script> |
ckfinder用于配置上传文件的请求路径
文件上传配置说明文档:https://ckeditor.com/docs/ckeditor5/latest/features/images/image-upload/ckfinder.html
返回JSON示例:
{"fileName":"ba24cb71398849d398330c23b2cceb9a.jpg","uploaded":1,"url":"/uploads/20220521/ba24cb71398849d398330c23b2cceb9a.jpg"
第三步:服务端上传设置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | [HttpPost] [Route( "api/upload" )] [AllowAnonymous] public async Task<IActionResult> UploadFileAsync(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 }); } |
最终效果:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步