Asp.Net Core中配置使用Kindeditor富文本編輯器實現圖片上傳和截圖上傳及文件管理和上傳(開源代碼.net core3.0)

原文: Asp.Net Core中配置使用Kindeditor富文本編輯器實現圖片上傳和截圖上傳及文件管理和上傳(開源代碼.net core3.0)

KindEditor使用JavaScript編寫,能夠無縫的於Java、.NET、PHP、ASP等程序接合。 KindEditor很是適合在CMS、商城、論壇、博客、Wiki、電子郵件等互聯網應用上使用,2006年7月首次發佈2.0以來,KindEditor依靠出色的用戶體驗和領先的技術不斷擴大編輯器市場佔有率,目前在國內已經成爲最受歡迎的編輯器之一。css

然而不少人缺爲在Asp.Net Core中的使用在發愁,因而這個開源Demo就這樣產生了,那麼我如今給各位介紹下它的快速使用吧!html

1、前端配置前端

1.首先引用相關文件jquery

<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.創建編輯器標籤(已有的數據直接渲染在標籤內便可加載至編輯器)git

<textarea name="content" style="width:100%;height:450px;" id="MyEidtor">@Html.Raw(Model.Context)</textarea>

3.初始化編輯器,並配置圖片及文件管理、上傳github

複製代碼
KindEditor.ready(function (K) {
        window.editor = K.create('#MyEidtor', {
            uploadJson: '../../Editor/KindSaveFiles?Title=@Html.Raw(Model.Title)&ContextId=@Model.Id',
            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&Title=@Html.Raw(Model.Title)&ContextId=@Model.Id',
                                        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.獲取數據保存web

 

function btnSave() {
        alert(window.editor.html());//獲取了數據,保存就沒問題了吧!
    }

 

2、後臺配置接收文件處理並返回預約格式的json數據ajax

複製代碼
#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
複製代碼

其中文件讀取不明白的能夠參考我以前的博客json

 

實現後效果如圖:服務器

 

開源地址 動動小手,點個推薦吧!

 

注意:咱們機遇屋該項目將長期爲你們提供asp.net core各類好用demo,旨在幫助.net開發者提高競爭力和開發速度,建議儘早收藏該模板集合項目

相關文章
相關標籤/搜索