KindEditor 编辑器在springboot使用

  • 官网下载kindEditor
    • 解决视频上传问题

官网下载kindEditor

  **1.  **官网地址 : http://kindeditor.net/down.php****

2.下载后解压;将解压文件引入到项目中

由于在java中使用;去掉不用的文件 asp,asp.net jsp;

3.引入js,我这里使用的是thymeleaf模板
4.html页面引入 ;也可以在页面直接引入js ; 添加文本框

   <th:block th:include="include :: kindEditor" />添加页面:<textarea style="width: 100%;height:400px;" name="context"></textarea>编辑页面:<textarea  style="width: 100%;height:400px;" name="context" th:field="*{context}"></textarea>

5. 初始化富文本框


```var editor;KindEditor.ready(function (K) {editor = K.create('textarea[name="context"]', {allowImageUpload:true,allowImageRemote: false,//是否允许浏览服务器已上传文件,默认是falseallowFileManager: true,uploadJson :"/kindEditor/uploadFile",fileManagerJson: "/kindEditor/fileManagerJson",afterBlur: function(){this.sync();},afterUpload : function(url, data, name) { //上传文件后执行的回调函数,必须为3个参数if (name == "image" || name == "multiimage") { //单个和批量上传图片时var img = new Image();img.src = url;img.onload = function () { //图片必须加载完成才能获取尺寸}}}});});

后台代码


@Controller
@RequestMapping("/kindEditor")
@Slf4j
public class KinUploadController extends BaseController {@Autowiredprivate UploadFilePathConfig filePathConfig;@Autowiredprivate ServerConfig serverConfig;/*** 提供KindEditor作文件上传使用* @param request* @param response* @throws Exception*/@PostMapping("/uploadFile")public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {PrintWriter writer = response.getWriter();String datePath = DateUtils.datePath(new Date());// 文件保存目录路径String savePath = filePathConfig.getUploadFolder()+datePath;// String savePath = Global.getUploadPath();//  String saveUrl = filePathConfig.getBaseUrl() + File.separatorChar + "static/image" + File.separatorChar;String saveUrl = serverConfig.getUrl() + File.separatorChar + "static/image/"+datePath+"/" + File.separatorChar;// 定义允许上传的文件扩展名HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp,JPG");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,pdf");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");// 最大文件大小// long maxSize = 1000000;response.setContentType("text/html; charset=UTF-8");if (!ServletFileUpload.isMultipartContent(request)) {writer.println(error("请选择文件。"));return ;}File uploadDir = new File(savePath);// 判断文件夹是否存在,如果不存在则创建文件夹if (!uploadDir.exists()) {uploadDir.mkdirs();}// 检查目录写权限if (!uploadDir.canWrite()) {writer.println(error("上传目录没有写权限。"));return ;}String dirName = request.getParameter("dir");if (dirName == null) {dirName = "image";}if (!extMap.containsKey(dirName)) {writer.println(error("目录名不正确。"));return ;}MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;Map<String, MultipartFile> fileMap = mRequest.getFileMap();String fileName = null;for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext();) {Map.Entry<String, MultipartFile> entry = it.next();MultipartFile mFile = entry.getValue();fileName = mFile.getOriginalFilename();// 检查文件大小/*  if (mFile.getSize() > maxSize) {writer.println(error("上传文件大小超过限制。"));return ;}*/String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {writer.println(error("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));return;}UUID uuid = UUID.randomUUID();String path = savePath +"/"+ uuid.toString() + "." + fileExt;saveUrl = saveUrl + uuid.toString() + "." + fileExt;System.out.println("path=========="+path);BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path));FileCopyUtils.copy(mFile.getInputStream(), outputStream);log.info("【提交图片】参数正确, saveUrl={}",saveUrl);JSONObject obj = new JSONObject();obj.put("error", 0);obj.put("url", saveUrl);writer.println(obj.toString());}}@RequestMapping("/fileManagerJson")public void fileManagerJson(HttpServletRequest request, HttpServletResponse response) throws Exception {response.setContentType("application/json; charset=UTF-8");PrintWriter out = response.getWriter();//根目录路径,可以指定绝对路径,比如 /var/www/attached/String rootPath = Global.getUploadPath() + "/attached/";//根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/String rootUrl = request.getContextPath() + "/attached/";//图片扩展名String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"};String dirName = request.getParameter("dir");if (dirName != null) {if (!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)) {out.println("Invalid Directory name.");return;}rootPath += dirName + "/";rootUrl += dirName + "/";File saveDirFile = new File(rootPath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}}//根据path参数,设置各路径和URLString path = request.getParameter("path") != null ? request.getParameter("path") : "";String currentPath = rootPath + path;String currentUrl = rootUrl + path;String currentDirPath = path;String moveupDirPath = "";if (!"".equals(path)) {String str = currentDirPath.substring(0, currentDirPath.length() - 1);moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";}//排序形式,name or size or typeString order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";//不允许使用..移动到上一级目录if (path.indexOf("..") >= 0) {out.println("Access is not allowed.");return;}//最后一个字符不是/if (!"".equals(path) && !path.endsWith("/")) {out.println("Parameter is not valid.");return;}//目录不存在或不是目录File currentPathFile = new File(currentPath);if (!currentPathFile.isDirectory()) {out.println("Directory does not exist.");return;}//遍历目录取的文件信息List<Hashtable> fileList = new ArrayList<Hashtable>();if (currentPathFile.listFiles() != null) {for (File file : currentPathFile.listFiles()) {Hashtable<String, Object> hash = new Hashtable<String, Object>();String fileName = file.getName();if (file.isDirectory()) {hash.put("is_dir", true);hash.put("has_file", (file.listFiles() != null));hash.put("filesize", 0L);hash.put("is_photo", false);hash.put("filetype", "");} else if (file.isFile()) {String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();hash.put("is_dir", false);hash.put("has_file", false);hash.put("filesize", file.length());hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));hash.put("filetype", fileExt);}hash.put("filename", fileName);hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));fileList.add(hash);}}if ("size".equals(order)) {Collections.sort(fileList, new SizeComparator());} else if ("type".equals(order)) {Collections.sort(fileList, new TypeComparator());} else {Collections.sort(fileList, new NameComparator());}JSONObject result = new JSONObject();result.put("moveup_dir_path", moveupDirPath);result.put("current_dir_path", currentDirPath);result.put("current_url", currentUrl);result.put("total_count", fileList.size());result.put("file_list", fileList);out.println(result.toJSONString());}}public class SizeComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {return 1;} else {if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {return 1;} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {return -1;} else {return 0;}}}
}public class TypeComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {return 1;} else {return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));}}}public class NameComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {return 1;} else {return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));}}}

解决视频上传问题

由于kinEditor中视频标签是,h5页面可能不支持,我们需要修改kindeditor-all.js文件

1-1. 打开kindeditor-all.js 在304行的地方添加 Video标签

       video: ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autoplay', 'quality', '.width', '.height', 'align', 'controls', 'muted','controlslist'],

1-2. 然后找到 _mediaEmbed(attrs)方法;大概在 955 行

function _mediaEmbed(attrs) {var html = '<embed ';_each(attrs, function(key, val) {html += key + '="' + val + '" ';});html += '/>';return html;
}****替换为:****function _mediaEmbed(attrs) {var html = '<embed ';_each(attrs, function(key, val) {html += key + '="' + val + '" ';});html += '/>';// 一段简单的代码 解决视频上传问题if (attrs.type=="video/mp4"){var html = '<video ';_each(attrs, function(key, val) {html += key + '="' + val + '" ';});html += 'controls="controls" />';}return html;}

1-3 找到 _mediaType(src)函数; 大概在929左右

**在这个方法中添加**
if (/\.(mp4)(\?|$)/i.test(src)) {return 'video/mp4';}if (/\.(ogg)(\?|$)/i.test(src)) {return 'video/ogg';}if (/\.(webm)(\?|$)/i.test(src)) {return 'video/webm';}**添加后:**function _mediaType(src) {if (/\.(rm|rmvb)(\?|$)/i.test(src)) {return 'audio/x-pn-realaudio-plugin';}if (/\.(swf|flv)(\?|$)/i.test(src)) {return 'application/x-shockwave-flash';}if (/\.(mp4)(\?|$)/i.test(src)) {return 'video/mp4';}if (/\.(ogg)(\?|$)/i.test(src)) {return 'video/ogg';}if (/\.(webm)(\?|$)/i.test(src)) {return 'video/webm';}return 'video/x-ms-asf-plugin';
}

后台上传效果:

页面展示效果

KindEditor 编辑器在springboot使用相关推荐

  1. php网页添加图片的代码,天天查询-PHP版的kindeditor编辑器加图片上传水印功能

    首先简单介绍一下kindeditor编辑器: KindEditor 是一套开源的在线HTML编辑器,开发人员可以用 KindEditor 把传统的多行文本输入框(textarea)替换为可视化的富文本 ...

  2. DWZ与KindEditor编辑器的整合

    原文:DWZ与KindEditor编辑器的整合 DWZ自带的编辑器是xheditor,可能很多人用不习惯.就像我,习惯用kindeditor了.现在就来说说如何整合dwz和kindeditor. 一. ...

  3. KindEditor编辑器在ASP.NET中的使用

    KindEditor编辑器在ASP.NET中的使用 最近做的项目中都有用到富文本编辑器,一直在寻找最后用的富文本编辑器,之前用过CKEditor,也用过UEditor,这次打算用 一下KindEdit ...

  4. kindeditor编辑器和图片上传独立分开的配置细节

    关于kindeditor编辑器上传按钮的异步加载最关键的部署问题,它的上传图片的组件都已经封装得很好了的,只需要监听到页面按钮的点击事件给编辑器对象传递一些对应的初始化参数即可显示图片上传的弹窗实现异 ...

  5. 如何在一个页面添加多个不同的kindeditor编辑器

    kindeditor官方下载地址:http://kindeditor.net/down.php    (入门必看)kindeditor官方文档:http://kindeditor.net/doc.ph ...

  6. KindEditor编辑器结合EasyUi

    KindEditor编辑器 var editor;//初始化编辑器 editor = KindEditor.create('#descriptionKindEditorU', {//创建编辑器item ...

  7. KindEditor编辑器上传图片超过限制

    使用KindEditor编辑器上传较大图片时,会出现如下图所示的错误: 超过php.ini允许的大小这样的问题需要到php.ini文件中将upload_max_filesize = 2M的限制大小修改 ...

  8. 关于kindeditor编辑器批量上传图片不显示添加图片按钮的问题

    今天在项目里发现kindeditor编辑器批量上传图片不显示添加文件按钮,去官网看demo是有的,经过浏览器debug发现是由于 multiimage.js文件的一个时间参数传递的不对, 很奇怪,改为 ...

  9. 如何在一个页面上使用多个KindEditor编辑器并将值传递到服务器端

    如何在一个页面上使用多个KindEditor编辑器并将值传递到服务器端 1.声明一个editor数组: 2.将之前的编辑器显示行代码: 3.传递KindEditor所填写的相关数据: 今天使用Kind ...

最新文章

  1. 前景检测算法_4(opencv自带GMM)
  2. php autoload静态,Composer 中自动加载 autoload_static 问题
  3. ABAddressBookSave关于保存到通讯录失败的问题
  4. 查找表的原理与结构 什么是竞争与冒险现象?怎样判断?如何消除?
  5. alert 标题_[SwiftUI 知识碎片] Button、Image 和 Alert
  6. 鸿蒙os事例代码,鸿蒙HarmonyOS App开发造轮子之自定义圆形图片组件的实例代码
  7. iOS常用的存储方式介绍
  8. python中re模块_Python中re(正则表达式)模块学习
  9. Swift游戏实战-跑酷熊猫 12 与平台的碰撞
  10. ❤️什么是Java 面向对象《装、继承、多态、抽象》?建议收藏)❤️
  11. 数据库 事务提交和回滚
  12. 【matlab安装】手把手图文并茂安装matlab2021(win10版)
  13. 周立功USBCAN-II的Python调用
  14. 人民日报申论万能结构
  15. 100部好看的校园喜剧片(可练习英文)+美国校园青春励志电影+25部口语练习电影+20部最浪漫电影
  16. oracle开源数据库审计,oracle数据库审计
  17. 美国挡不住商汤:仅一周后重启IPO,新增基石投资3.8亿元,年前30号挂牌上市
  18. 【OpenCV+Qt】使用车牌识别系统EasyPR识别车牌号
  19. 一维信号 处理分析 c语言,信号处理与分析课程设计训练任务书.doc
  20. 官网消息!预聘制教师,年薪不低于40万!这所高校强势引才!

热门文章

  1. java.util.Scanner简单介绍
  2. 说个特别适合穷人创业赚钱的方法吧
  3. jenkins多任务并发构建
  4. 一个废物大学生的学习日常day1(10月23日)(折线图与地图的绘制
  5. Android写的播放器控制之starService和bindService混合使用知识总结
  6. c++:vector对象的增长
  7. 计算机辅助设计结课,计算机辅助设计课程小结
  8. [HNOI]2003 消防局的建立
  9. View 的四种 OnClick 方式
  10. 新安装的mysql登陆时出现Access denied for user ‘root‘@‘localhost‘ (using password: NO)