KindEditor使用JavaScript編寫,可以無縫的於Java、.NET、PHP、ASP等程式接合。 KindEditor非常適合在CMS、商城、論壇、博客、Wiki、電子郵件等互聯網應用上使用,2006年7月首次發佈2.0以來,KindEditor依靠出色的用戶體驗和領先的技術不斷擴大編輯 ...
KindEditor使用JavaScript編寫,可以無縫的於Java、.NET、PHP、ASP等程式接合。 KindEditor非常適合在CMS、商城、論壇、博客、Wiki、電子郵件等互聯網應用上使用,2006年7月首次發佈2.0以來,KindEditor依靠出色的用戶體驗和領先的技術不斷擴大編輯器市場占有率,目前在國內已經成為最受歡迎的編輯器之一。
然而很多人缺為在Asp.Net Core中的使用在發愁,於是這個開源Demo就這樣產生了,那麼我現在給各位介紹下它的快速使用吧!
一、前端配置
1.首先引用相關文件
<link rel="stylesheet" href="~/Lib/Kindeditor/themes/default/default.css" /> <link rel="stylesheet" href="~/Lib/Kindeditor/plugins/code/prettify.css" /> <script charset="utf-8" src="~/Lib/Kindeditor/kindeditor-all.js"></script> <script charset="utf-8" src="~/Lib/Kindeditor/lang/zh-CN.js"></script> <script charset="utf-8" src="~/Lib/Kindeditor/plugins/code/prettify.js"></script>
2.建立編輯器標簽(已有的數據直接渲染在標簽內即可載入至編輯器)
<textarea name="content" style="width:100%;height:450px;" id="MyEidtor">@Html.Raw(Model.Context)</textarea>
3.初始化編輯器,並配置圖片及文件管理、上傳
KindEditor.ready(function (K) { window.editor = K.create('#MyEidtor', { uploadJson: '../../Editor/[email protected](Model.Title)&[email protected]', fileManagerJson: '@Url.Action("KindFileManager", "Editor")', allowFileManager: true, autoHeightMode : true, afterCreate: function () { var editerDoc = this.edit.doc;//得到編輯器的文檔對象 //監聽粘貼事件, 包括右鍵粘貼和ctrl+v $(editerDoc).bind('paste', null, function (e) { var ele = e.originalEvent.clipboardData.items; for (var i = 0; i < ele.length; ++i) { //判斷文件類型 if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -1) { var file = ele[i].getAsFile();//得到二進位數據 //創建表單對象,建立name=value的表單數據。 var formData = new FormData(); formData.append("imgFile", file);//name,value //用jquery Ajax 上傳二進位數據 $.ajax({ url: '../../Editor/KindSaveFiles?dir=image&[email protected](Model.Title)&[email protected]', type: 'POST', data: formData, // 告訴jQuery不要去處理髮送的數據 processData: false, // 告訴jQuery不要去設置Content-Type請求頭 contentType: false, dataType: "json", beforeSend: function () { //console.log("正在進行,請稍候"); }, success: function (responseStr) { //上傳完之後,生成圖片標簽回顯圖片,假定伺服器返回url。 var src = responseStr.url; var imgTag = "<img src='" + src + "' border='0'/>"; //console.info(imgTag); //kindeditor提供了一個在焦點位置插入HTML的函數,調用此函數即可。 editor.insertHtml(imgTag); }, error: function (responseStr) { console.log("error"); } }); } } } ) } }); });
4.獲取數據保存
function btnSave() { alert(window.editor.html());//獲取了數據,保存就沒問題了吧! }
二、後臺配置接收文件處理並返回預定格式的json數據
#region Kindeditor private string KindStr = "Kind";//首碼文件名,可自行修改 public IActionResult Kindeditor() { Article article = new Article(); article.Context = "這是編輯器測試數據!"; article.Id = 1; article.Title = "測試"; return View(article); } public async Task<IActionResult> KindSaveFiles(string dir, string Title, long ContextId = 0, long ArticleTypeId = 0) { if (Request.Form.Files.Count() == 0) { return showError("請選擇上傳的文件"); } var file = Request.Form.Files[0];//kindeditor的上傳文件控制項,一次只傳一個文件 //定義允許上傳的文件擴展名 Hashtable extTable = new Hashtable(); extTable.Add("image", "gif,jpg,jpeg,png,bmp"); extTable.Add("flash", "swf,flv"); extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4"); extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); if (String.IsNullOrEmpty(dir)) { dir = "image"; } string fName = ""; string fileName = ""; string md5 = CommonHelper.CalcMD5(file.OpenReadStream()); String fileExt = Path.GetExtension(file.FileName).ToLower(); if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dir]).Split(','), fileExt.Substring(1).ToLower()) == -1) { return showError("上傳文件擴展名是不允許的擴展名。\n只允許" + ((String)extTable[dir]) + "格式。"); } //創建文件夾 string dirPath = ConfigHelper.GetSectionValue("FileMap:FilePath") + "\\"+ KindStr + "\\" + dir + "\\"; string webPath = "/" + KindStr + "/" + dir + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo); dirPath += ymd + "\\"; webPath += ymd + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } string suijishu = Math.Abs(Guid.NewGuid().GetHashCode()).ToString(); String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_" + suijishu, DateTimeFormatInfo.InvariantInfo) + fileExt; fileName = dirPath + $@"{newFileName}"; using (FileStream fs = System.IO.File.Create(fileName)) { await file.CopyToAsync(fs); fs.Flush(); } fName = ConfigHelper.GetSectionValue("FileMap:FileWeb") + webPath + newFileName; Hashtable hash = new Hashtable(); hash["error"] = 0; hash["url"] = fName; return Json(hash); } [NonAction] private IActionResult showError(string message) { Hashtable hash = new Hashtable(); hash["error"] = 1; hash["message"] = message; return Json(hash); } public IActionResult KindFileManager() { String rootUrl = "/"+ KindStr + "/"; //圖片擴展名 String fileTypes = "gif,jpg,jpeg,png,bmp"; String currentPath = ""; String currentUrl = ""; String currentDirPath = ""; String moveupDirPath = ""; String dirPath = ConfigHelper.GetSectionValue("FileMap:FilePath") + "\\Kind" + "\\"; String dirName = Request.Query["dir"]; if (!String.IsNullOrEmpty(dirName)) { if (Array.IndexOf("image,flash,media,file".Split(','), dirName) == -1) { return showError("目錄錯誤"); } dirPath += dirName + "/"; rootUrl += dirName + "/"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } } //根據path參數,設置各路徑和URL String path = Request.Query["path"]; path = String.IsNullOrEmpty(path) ? "" : path; if (path == "") { currentPath = dirPath; currentUrl = rootUrl; currentDirPath = ""; moveupDirPath = ""; } else { currentPath = dirPath + path; currentUrl = rootUrl + path; currentDirPath = path; moveupDirPath = Regex.Replace(currentDirPath, @"(.*?)[^\/]+\/$", "$1"); } //排序形式,name or size or type String order = Request.Query["order"]; order = String.IsNullOrEmpty(order) ? "" : order.ToLower(); //不允許使用..移動到上一級目錄 if (Regex.IsMatch(path, @"\.\.")) { return showError("Access is not allowed."); } //最後一個字元不是/ if (path != "" && !path.EndsWith("/")) { return showError("Parameter is not valid."); } //目錄不存在或不是目錄 if (!Directory.Exists(currentPath)) { return showError("Directory does not exist."); } //遍歷目錄取得文件信息 string[] dirList = Directory.GetDirectories(currentPath); string[] fileList = Directory.GetFiles(currentPath); switch (order) { case "size": Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new SizeSorter()); break; case "type": Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new TypeSorter()); break; case "name": default: Array.Sort(dirList, new NameSorter()); Array.Sort(fileList, new NameSorter()); break; } Hashtable result = new Hashtable(); result["moveup_dir_path"] = moveupDirPath; result["current_dir_path"] = currentDirPath; result["current_url"] = currentUrl; result["total_count"] = dirList.Length + fileList.Length; List<Hashtable> dirFileList = new List<Hashtable>(); result["file_list"] = dirFileList; for (int i = 0; i < dirList.Length; i++) { DirectoryInfo dir = new DirectoryInfo(dirList[i]); Hashtable hash = new Hashtable(); hash["is_dir"] = true; hash["has_file"] = (dir.GetFileSystemInfos().Length > 0); hash["filesize"] = 0; hash["is_photo"] = false; hash["filetype"] = ""; hash["filename"] = dir.Name; hash["datetime"] = dir.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"); dirFileList.Add(hash); } for (int i = 0; i < fileList.Length; i++) { FileInfo file = new FileInfo(fileList[i]); Hashtable hash = new Hashtable(); hash["is_dir"] = false; hash["has_file"] = false; hash["filesize"] = file.Length; hash["is_photo"] = (Array.IndexOf(fileTypes.Split(','), file.Extension.Substring(1).ToLower()) >= 0); hash["filetype"] = file.Extension.Substring(1); hash["filename"] = file.Name; hash["datetime"] = file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"); dirFileList.Add(hash); } return Json(result); } public class NameSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.FullName.CompareTo(yInfo.FullName); } } public class SizeSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.Length.CompareTo(yInfo.Length); } } public class TypeSorter : IComparer { public int Compare(object x, object y) { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } FileInfo xInfo = new FileInfo(x.ToString()); FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.Extension.CompareTo(yInfo.Extension); } } #endregion
其中文件讀取不明白的可以參考我之前的博客
實現後效果如圖:
開源地址 動動小手,點個推薦吧!
註意:我們機遇屋該項目將長期為大家提供asp.net core各種好用demo,旨在幫助.net開發者提升競爭力和開發速度,建議儘早收藏該模板集合項目。