版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31653405/article/details/83344882
效果图:
/**
如果在编辑器中,某个功能不想让他显示,则可在kindeditor-all.js中的K.options = { items (通常在263行处)}
删除相应的功能名称(在浏览器中,用F12找相应功能的data-name)即可
参考文档:https://blog.csdn.net/qq_30258957/article/details/78762464
http://kindeditor.net/doc.php 官网
**/
html代码
<!-- 添加文本编辑器插件 -->
<script charset="utf-8" type="text/javascript" src="/kindeditor/kindeditor-all.js"></script>
<script charset="utf-8" type="text/javascript" src="/kindeditor/lang/zh-CN.js"></script>
<script src="/kindeditor/themes/default/default.css" type="text/css" rel="stylesheet"></script>
<!--编写文本区域-->
<textarea id="editor_id" name="content" style="width:700px;height:200px;visibility:hidden;"></textarea>
<script type="text/javascript">
var editor1;
/**页面初始化 创建文本编辑器工具**/
KindEditor.ready(function(K) {
//定义生成编辑器的文本类型
editor1 = K.create('textarea[name="content"]', {
cssPath : '../plugins/code/prettify.css',
allowImageUpload: true, //上传图片框本地上传的功能,false为隐藏,默认为true
allowImageRemote : false, //上传图片框网络图片的功能,false为隐藏,默认为true
formatUploadUrl:false,
uploadJson : '/kindEditor/upLoad',//文件上传请求后台路径
allowFileManager : true,
afterCreate : function() {
var self = this;
K.ctrl(document, 13, function() {
self.sync();
document.forms['example'].submit();
});
K.ctrl(self.edit.doc, 13, function() {
self.sync();
document.forms['example'].submit();
});
}
});
prettyPrint();
});
</script>
上传图片的工具类:
@WebServlet("/kindEditor/upLoad")
public class KindEditorUpload extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置Response响应的编码
resp.setContentType("text/html; charset=UTF-8");
//获取一个Response的Write对象
PrintWriter writer = resp.getWriter();
//文件保存目录路径
String savePath = "D:\\images/";
String saveUrl = savePath;
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
// 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,txt,zip,rar,gz,bz2");
//最大文件大小
long maxSize = 1000000;
String dirName = req.getParameter("dir");
if (dirName == null) {
dirName = "image";
}
if (!extMap.containsKey(dirName)) {
writer.println(getError("目录名不正确。"));
return;
}
//创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List items = null;
try {
items = upload.parseRequest(req);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
String fileName = item.getName();
long fileSize = item.getSize();
if (!item.isFormField()) {
//检查文件大小
if (item.getSize() > maxSize) {
writer.println(getError("上传文件大小超过限制。"));
return;
}
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
writer.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
try {
File uploadedFile = new File(savePath, newFileName);
item.write(uploadedFile);
} catch (Exception e) {
writer.println(getError("上传文件失败。"));
return;
}
String url = "http://localhost:8080/images/image/"+ ymd + "/" + newFileName;//显示图片的主要路径
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url",url);
writer.println(obj.toString());
}
}
//将writer对象中的内容输出
writer.flush();
//关闭writer对象
writer.close();
}
//一个私有的方法,用于响应错误信息
private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
return obj.toString();
}
}
显示图片工具类:
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Value("${cbs.imagesPath}")
private String mImagesPath;
//访问图片方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
if(imagesPath.indexOf(".jar")>0){
imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
}else if(imagesPath.indexOf("classes")>0){
imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
}
imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
mImagesPath = imagesPath;
}
LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);
registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);//访问图片的路径
super.addResourceHandlers(registry);
}
}
页面显示文本编辑内容:
<span id="productIntroduceId"></span> <!--将要显示文本编辑器内容部分-->
<input id="productIntroduce" th:value="${product.productIntroduce}" hidden="hidden"><!--获取文本编辑器内容部分-->
<script type="text/javascript">
window.onload=function () {//将文本编辑器内容 用js进行替换显示
document.getElementById("productIntroduceId").innerHTML=$("#productIntroduce").val();
}
</script>
以上是自己整理的,并测试过,可以直接用
----------------------------------------------------------------------------------------------------------------
文章中,有问题,可以在评论区评论,一起探讨编程中奥秘!
----------------------------------------------------------------------------------------------------------------
来都来了,代码看都看了,那就留个言呗,可以互动下!
----------------------------------------------------------------------------------------------------------------
转载声明:本文为博主原创文章,未经博主允许不得转载