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 = ; i < ele.length; ++i) {
//判断文件类型
if (ele[i].kind == 'file' && ele[i].type.indexOf('image/') !== -) {
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 = ;
article.Title = "测试";
return View(article);
} public async Task<IActionResult> KindSaveFiles(string dir, string Title, long ContextId = , long ArticleTypeId = )
{
if (Request.Form.Files.Count() == )
{
return showError("请选择上传的文件");
} var file = Request.Form.Files[];//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().ToLower()) == -)
{
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"] = ;
hash["url"] = fName;
return Json(hash);
} [NonAction]
private IActionResult showError(string message)
{
Hashtable hash = new Hashtable();
hash["error"] = ;
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) == -)
{
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 = ; i < dirList.Length; i++)
{
DirectoryInfo dir = new DirectoryInfo(dirList[i]);
Hashtable hash = new Hashtable();
hash["is_dir"] = true;
hash["has_file"] = (dir.GetFileSystemInfos().Length > );
hash["filesize"] = ;
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 = ; 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().ToLower()) >= );
hash["filetype"] = file.Extension.Substring();
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 ;
}
if (x == null)
{
return -;
}
if (y == null)
{
return ;
}
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 ;
}
if (x == null)
{
return -;
}
if (y == null)
{
return ;
}
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 ;
}
if (x == null)
{
return -;
}
if (y == null)
{
return ;
}
FileInfo xInfo = new FileInfo(x.ToString());
FileInfo yInfo = new FileInfo(y.ToString()); return xInfo.Extension.CompareTo(yInfo.Extension);
}
}
#endregion

其中文件读取不明白的可以参考我之前的博客

实现后效果如图:

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

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

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

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

    我们的富文本编辑器不能没有图片上传尤其是截图上传,下面我来教大家怎么实现MarkDown富文本编辑器截图上传和图片上传. 1.配置编辑器到html页 <div id="test-edi ...

  2. 在Asp.Net或.Net Core中配置使用MarkDown富文本编辑器有开源模板代码(代码是.net core3.0版本)

    研究如何使用Markdown你们可能要花好几天才能搞定,但是看我的文章或者下载了源码,你搞定一般在10分钟之内.我先给各位介绍下它: Markdown 是一种轻量级标记语言,它允许人们使用易读易写的纯 ...

  3. django的admin或者应用中使用KindEditor富文本编辑器

    由于django后台管理没有富文本编辑器,看着好丑,展示出来的页面不美观,无法做到所见即所得的编辑方式,所以我们需要引入第三方富文本编辑器. 之前找了好多文档已经博客才把这个功能做出来,有些博客虽然写 ...

  4. kindeditor富文本编辑器初步使用教程

    下载kindeditor 可以选择去官网下载(http://kindeditor.net/down.php),不过要FQ:或者直接CSDNhttp://download.csdn.net/downlo ...

  5. (转)淘淘商城系列——KindEditor富文本编辑器的使用

    http://blog.csdn.net/yerenyuan_pku/article/details/72809794 通过上文的学习,我们知道了怎样解决KindEditor富文本编辑器上传图片时的浏 ...

  6. (转)学习淘淘商城第二十二课(KindEditor富文本编辑器的使用)

    http://blog.csdn.net/u012453843/article/details/70184155 上节课我们一起学习了怎样解决KindEditor富文本编辑器上传图片的浏览器兼容性问题 ...

  7. coding++:快速构建 kindeditor 富文本编辑器(一)

    此案例 demo 为 SpringBoot 开发 1.官网下载相关资源包:http://kindeditor.net/down.php 2.编写页面(引入相关JS) <!DOCTYPE html ...

  8. KindEditor富文本编辑器使用

    我的博客本来打算使用layui的富文本编辑器,但是出了一个问题,无法获取编辑器内容,我参考官方文档,获取内容也就那几个方法而已,但是引入进去后始终获取的值为空,百度和bing都试过了,但是始终还是获取 ...

  9. Vue富文本编辑器(图片拖拽缩放)

    富文本编辑器(图片拖拽缩放) 需求: 根据业务要求,需要能够上传图片,且上传的图片能在移动端中占满屏幕宽度,故需要能等比缩放上传的图片,还需要能拖拽.缩放.改变图片大小.尝试多个第三方富文本编辑器,很 ...

随机推荐

  1. 报表统计——java实现查询某年12个月数据,没数据补0

    一般图表绘制例如echarts等,返回数据格式都大同小异.重点是利用sql或者java实现数据格式的转型,接下来是关键部分: 1.mapper层sql语句,返回统计好的月份与对应月份的数据. < ...

  2. while 格式化输出 编码初识

    1.while循环 while 关键字 空格 条件 冒号 缩进 循环体 while 3>2: print("好嗨呦") print("你的骆驼") pri ...

  3. JVM(五)回收机制

    1.对象的引用 JDK1.2之后,对象的引用分为了四种情况    强引用:Object obj = new Object():只要强引用还在,垃圾回收器就永远不会收集被引用的对象.    软引用:So ...

  4. win10家庭版升级专业版

    在网上随便百度一个产品密钥,记得一定要先断网(这个很重要),否则很难升级. 升级之后发现产品未激活,下载KMS激活一下就可以了.

  5. Xshell、Xftp 5、6 解决“要继续使用此程序,您必须应用最新的更新或使用新版本”

    今天打开Xshell.Xftp,突然弹出“要继续使用此程序,您必须应用最新的更新或使用新版本”. 后来经过一番搜索发现,XShell配置文件中写入了强制升级时间,这个版本是2017年12月27日发布的 ...

  6. CSDN VIP如何添加自定义栏目

    几个月前我也开始在csdn上开了博客,一来给自己加几个少的可怜的流量,再者,让公众号的原创文章获得更多的曝光,让有需要的同学看到. 写过csdn博客的同学都知道,默认只有打赏c币功能:也没有专门广告位 ...

  7. What is neural network?

    It is a powerful learning algoithm inspired by how the brain work. Example 1 - single neural network ...

  8. 为什么要实现 IDisposable 接口?

    一.背景 最近在精读 <CLR Via C#>和 <Effective C#> 的时候,发现的一个问题点.一般来说,我们实现 IDisposable 接口,是为了释放托管资源和 ...

  9. vc++源码免杀特殊技巧

    一.Debug 和 Release 编译方式的区别: Debug 通常称为调试版本,它包含调试信息,并且不作任何优化,便于程序员调试程序.Release 称为发布版本,它往往是进行了各种优化,使得程序 ...

  10. PHP7源码之array_unique函数分析

    以下源码基于 PHP 7.3.8 array array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) (PHP 4 >= ...