• Asp.Net Core中配置使用Kindeditor富文本编辑器实现图片上传和截图上传及文件管理和上传(开源代码.net core3.0)


    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="100%;height:450px;" id="MyEidtor">@Html.Raw(Model.Context)</textarea>

    3.初始化编辑器,并配置图片及文件管理、上传

    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.获取数据保存

    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("上传文件扩展名是不允许的扩展名。
    只允许" + ((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开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目

  • 相关阅读:
    微信被动回复用户消息
    微信接收普通消息接口
    THINKPHP nginx设置路由为PATHINFO模式
    php安装扩展步骤(redis)
    设计模式之单例模式
    设计模式之六大原则
    几个最常用的Mysql命令
    几个最常用的git命令
    VS使用WinRAR软件以命令行方式打包软件至一个exe
    智能指针unique_ptr的用法
  • 原文地址:https://www.cnblogs.com/jiyuwu/p/11797389.html
Copyright © 2020-2023  润新知