欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-19 19:37:17
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/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("上传文件扩展名是不允许的扩展名。\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中配置使用Kindeditor富文本编辑器实现图片上传和截图上传及文件管理和上传(开源代码.net core3.0)

 

开源地址 动动小手,点个推荐吧!

 

注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目