Java KindEditor 4 HTML编辑器 基本用法
1. Maven包 pom.xml
<!-- 父级 pom.xml-->
<properties>
<spring-boot.version>1.5.17.RELEASE</spring-boot.version>
</properties>
<dependencyManagement>
<dependencies>
<!--Spring IO 控制依赖版本适配-->
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Brussels-SR14</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--Spring Boot 控制依赖版本适配-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
</dependencies>
</dependencyManagement>
<!-- 子级 pom.xml-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
2. 环境 application.properties
# Base
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
# Mysql
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&serverTimezone=PRC&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=
# Mybatis
mybatis.mapper-locations=classpath:mapper/*.xml
# Html Template [LEGACYHTML5\u975E\u4E25\u683C, HTML5\u4E25\u683C]
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:views/
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.suffix=.html
3. 数据库 test
和数据表 user
及相关测试数据
CREATE DATABASE `test` DEFAULT CHARSET utf8;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`memo` varchar(2000) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
4. User.java(Entity)与 user
数据表字段对应
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 8755803182642361875L;
private Long id;
private String name;
private String memo;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
5. DAO(Data Access Object)数据访问接口 UserDao.java和实现类 UserDaoImpl.java
/**
* User的数据访问接口 UserDao.java
*/
import com.test.web3.entity.User;
public interface UserDao {
void create(final User user);
}
/**
* 实现类 UserDaoImpl.java
*/
import com.test.web3.entity.User;
import com.test.web3.dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SqlSession sqlSession;
static final String MAPPER = "com.test.web3.UserMapper.";
@Override
public void create(final User user) {
sqlSession.insert(MAPPER + "create", user);
}
}
6. UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.test.web3.UserMapper">
<insert id="create" parameterType="com.test.web3.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO
`user`
(`name`,`memo`)
VALUES
(#{name},#{memo})
</insert>
</mapper>
7. createUser.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- https://code.jquery.com/ -->
<script th:src="@{/jquery-1.12.4.min.js}"></script>
<!-- http://kindeditor.net 版本 4.x -->
<script th:src="@{/kindeditor/kindeditor-all-min.js}"></script>
<script th:src="@{/kindeditor/lang/zh-CN.js}"></script>
</head>
<body>
<h4>创建用户:</h4>
<div>
<form name="f" id="f" method="post" action="/createUser" enctype="multipart/form-data">
<table width="800" border="0" cellspacing="4" cellpadding="4">
<tr>
<td align="center" width="80">姓名: </td>
<td align="left"><input type="text" name="name" id="name" value="Shawn Joen"></td>
</tr>
<tr>
<td align="center">个人说明: </td>
<td align="left"><textarea name="memo" id="memo"></textarea></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="提交" onclick="createUser()"/></td>
</tr>
</table>
</form>
</div>
<script th:inline="javascript" type="text/javascript">
KindEditor.create('textarea[name="memo"]', {
uploadJson : "" + '/kindeditor/fileUpload',
fileManagerJson : "" + '/kindeditor/fileManager',
allowFileManager : true,
afterBlur: function() {this.sync()},
items : ['source', '|', 'undo', 'redo', '|', 'preview', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image','multiimage',
'flash', 'insertfile', 'table', 'hr', 'emoticons', 'pagebreak', 'link', 'unlink']
});
function createUser() {
var params = {},
nameInput = $('[name=name]');
params.name = $.trim(nameInput.val());
if (!params.name) {
alert('请输入姓名!');
nameInput.select();
return;
}
var data = new FormData($('form')[0]);
$.ajax({
url: '/createUser',
type: 'POST',
dataType: "json",
data: data,
cache: false,
contentType: false,
processData: false,
success: function(result) {
if (result.message) {
alert(result.message);
}
},
error: function() {
alert('error');
}
});
}
</script>
</body>
</html>
8. UserController.java(入口)
import com.test.web3.dao.UserDao;
import com.test.web3.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
public class UserController {
@Autowired
private UserDao userDao;
/**
* 创建用户
* */
@RequestMapping(value = "/createUser", method = RequestMethod.GET)
public String createUser() {
return "createUser";
}
@RequestMapping(value = "/createUser", method = RequestMethod.POST)
public @ResponseBody Map<String, String> createUser(@ModelAttribute("user") User user) {
/**
* 创建用户
* */
userDao.create(user);
Map<String, String> result = new HashMap<>();
result.put("message", "创建成功!");
return result;
}
}
9. 上传文件 和 其它工具类
import java.util.UUID;
public class CommonUtil {
public static String getUUID() {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return uuid;
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateUtil {
public static final String HH = "HH";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final DateTimeFormatter FORMATTER_HH = DateTimeFormatter.ofPattern(HH);
public static final DateTimeFormatter FORMATTER_YYYY_MM_DD = DateTimeFormatter.ofPattern(YYYY_MM_DD);
public static String getHH() {
return FORMATTER_HH.format(LocalDateTime.now());
}
public static String getYYYYMMDD() {
return FORMATTER_YYYY_MM_DD.format(LocalDateTime.now());
}
}
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
public class FileUtil {
final public static File makeEmptyFile(String URIPath) {
File newFile = new File(URIPath);
if (!newFile.getParentFile().exists()) {
newFile.getParentFile().mkdirs();
}
return newFile;
}
final public static StringBuilder uploadFiles(String rootPath, String fileURL, String folderType, MultipartFile files[]) throws IOException {
final StringBuilder filePaths = new StringBuilder();
for (MultipartFile file : files) {
if (file != null) {
String originalFilename = file.getOriginalFilename();
if (!file.isEmpty()) {
/**
* 文件相对路径
* */
String URIDir = File.separator + folderType + File.separator + DateUtil.getYYYYMMDD() + File.separator + DateUtil.getHH();
/**
* 设置文件名称
* */
String newFileName = URIDir + File.separator + CommonUtil.getUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
/**
* 文件绝对路径
* */
String realFilePath = rootPath + newFileName;
/**
* 创建空文件
* */
File newFile = FileUtil.makeEmptyFile(realFilePath);
/**
* 将文件数据写入磁盘
* */
file.transferTo(newFile);
if (filePaths.length() > 0) {
filePaths.append(",");
}
filePaths.append(fileURL + newFileName);
}
}
}
return filePaths;
}
}
10. 通过 KindEditor上传文件(入口)
import com.test.web3.util.FileUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("kindeditor")
public class KindEditorController {
/**
* 通过 Kindeditor上传文件
* */
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public Map<String, Object> fileUpload(@RequestParam(value = "dir", required = false, defaultValue="image") String dirName,
MultipartFile imgFile[], HttpServletResponse response) throws IOException {
response.setHeader("X-Frame-Options", "SAMEORIGIN");
Map<String, Object> result = new HashMap<>();
if (imgFile.length == 0) {
result.put("message", "请选择图片!");
return result;
}
if (dirName == null) {
dirName = "image";
}
/**
* 允许的文件类型
* */
final Map<String, String> extMap = new HashMap<>();
extMap.put("image", "gif,jpg,jpeg,png");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");
if (!extMap.containsKey(dirName)) {
result.put("message", "目录名不正确!");
return result;
}
final String[] fileExts = extMap.get(dirName).split(",");
for (MultipartFile file : imgFile) {
String originalFilename = file.getOriginalFilename();
if (!file.isEmpty()) {
String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.asList(fileExts).contains(fileExt)) {
result.put("message", "不允许上传的文件类型。\n只允许" + extMap.get(dirName) + "格式!");
return result;
}
}
}
/**
* 上传文件
* */
final StringBuilder filePaths = FileUtil.uploadFiles(
"d:\\phpStudy" + File.separator + "WWW" + File.separator + "wordpress-5.2.3-zh_CN" + File.separator + "wp-content" + File.separator + "uploads", /** 文件上传绝对路径*/
"http://127.0.0.1" + File.separator + "wp-content" + File.separator + "uploads", /** 打开相关文件的 网页地址*/
"temp", /** 指定目录*/
imgFile
);
if (filePaths.length() == 0) {
result.put("message", "请选择文件!");
return result;
}
/**
* 文件上传成功需要返回 error: 0, 否者上传成功后窗户不会关闭且文件也不显示在输入窗内
* */
result.put("error", 0);
result.put("message", "上传成功!");
result.put("url", filePaths.toString());
return result;
}
}
上传图效果
如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!