springboot中使⽤kindeditor富⽂本编辑器实现博客功能 kindeditor在之前已经⽤过,现在在springboot项⽬中使⽤。并且也在⾥⾯使⽤了图⽚上传以及回显等功能。
其实主要的功能是图⽚的处理:kindeditor对输⼊的内容会作为html标签处理,对于image的做法是先将图⽚传到后台服务器,然后上传成功之后回传图⽚的URL,之后内容中增加<img src='url'>进⾏回显,当然保存到数据库也是img标签进⾏保存的。
下⾯的代码涉及到了:Restful风格的请求、SpringMVC⽂件的上传、不配置虚拟路径的前提下请求图⽚资源、kindeditor、thymeleaf模板的使⽤。
1.⾸先编写接收kindeditor图⽚上传和图⽚请求的类:
package ller.user;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apachemons.io.FilenameUtils;
import org.apachemons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.qs.bean.user.Blogpicture;
import cn.qs.service.user.BlogPictureService;
import cn.qs.utils.FileHandleUtil;
import cn.qs.utils.UUIDUtil;
@Controller
@RequestMapping("blogPicture")
public class BlogPictureController {
private static final Logger logger = Logger(BlogPictureController.class);
@Autowired
private BlogPictureService blogPictureService;
/**
asp富文本编辑器* Restful风格获取图⽚
*
* @param request
* @param response
* @param pictureId
*/
@RequestMapping("/getPicture/{pictureId}")
public void getPicture(HttpServletRequest request, HttpServletResponse response, @PathVariable() String pictureId) {
FileInputStream in = null;
ServletOutputStream outputStream = null;
try {
String picturePath = PicturePathByPictureId(pictureId);
File fileByName = FileByName(picturePath);
in = new FileInputStream(fileByName);
outputStream = OutputStream();
outputStream = OutputStream();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(outputStream);
}
}
/**
* 图⽚上传
*
* @param imgFile
* @return
*/
@RequestMapping("/uploadPicture")
@ResponseBody
public Map<String, Object> uploadPicture(MultipartFile imgFile) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("error", 1);
if (imgFile == null) {
result.put("message", "⽂件没接到");
return result;
}
logger.debug("file -> {},viewId ->{}", OriginalFilename());
String fileOriName = OriginalFilename();// 获取原名称
String fileNowName = UUID2() + "." + Extension(fileOriName);// ⽣成唯⼀的名字
try {
FileHandleUtil.uploadSpringMVCFile(imgFile, fileNowName);
} catch (Exception e) {
<("uploadPicture error", e);
return result;
}
String id = UUID();
Blogpicture blogpicture = new Blogpicture();
blogpicture.setCreatetime(new Date());
blogpicture.setId(id);
blogpicture.setPath(fileNowName);
blogpicture.setOriginname(fileNowName);
blogPictureService.insert(blogpicture);
result.put("error", 0);
result.put("url", "/blogPicture/getPicture/" + id);
return result;
}
}
图⽚上传:参数接受名字必须是imgFile,否则接收不到⽂件。收到⽂件之后先⽣成⼀个全局唯⼀的名称然后保存到本地,并保存到数据库之后返回⼀个图⽚的URL例如: /blogPicture/getPicture/94995b51-901c-44e9-87ec-12c109098f5e
图⽚获取:通过restful风格的请求将图⽚的ID传到后台,根据ID查询到图⽚的路径,然后调⽤IOUtils
将⽂件流回传回去实现图⽚的src 请求显⽰拖。
FileHandleUtil类是图⽚保存以及获取,保存到本地的固定⽂件夹下⾯。
package cn.qs.utils;
import java.io.File;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apachemons.io.FileUtils;
import org.apachemons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileHandleUtil {
public static final String LANGUAGE = "zh";
public static final String COUNTRY = "CN";
private static String getProperties(String baseName, String section) {
String retValue = "";
try {
Locale locale = new Locale(LANGUAGE, COUNTRY);
ResourceBundle rb = Bundle(baseName, locale);
retValue = (String) rb.getObject(section);
} catch (Exception e) {
}
return retValue;
}
public static String getValue(String fileName, String key) {
String value = getProperties(fileName, key);
return value;
}
public static boolean deletePlainFile(String propertiesFileName, String fileName) {
if (fileName == null) {
return false;
}
String fileDir = StringUtils.Value("path", "picture"), "E:/picture/");
try {
FileUtils.deleteQuietly(new File(fileDir + fileName));
} catch (Exception e) {
return false;
}
return true;
}
public static boolean uploadSpringMVCFile(MultipartFile multipartFile, String fileName) throws Exception { String fileDir = StringUtils.Value("path", "picture"), "E:/picture/");
if (!new File(fileDir).exists()) {
new File(fileDir).mkdirs();
}
return true;
}
public static File getFileByName(String path) {
String fileDir = StringUtils.Value("path", "picture"), "E:/picture/");
return new File(fileDir+path);
}
}
2.前台界⾯准备富⽂本编辑器并且保存输⼊的信息到数据库
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>欢迎页⾯-X-admin2.0</title>
<meta name="renderer" content="webkit"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<meta name="viewport" content="width=device-width,user-scalable=yes, minimum-scale=0.4, initial-scale=0.8,target-densitydpi=low-dpi"/> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" th:href="${#ContextPath()+'/static/x-admin/css/font.css'}"/>
<link rel="stylesheet" th:href="${#ContextPath()+'/static/x-admin/css/xadmin.css'}"/>
<script type="text/javascript" th:src="${#ContextPath()+'/static/js/jquery.min.js'}" charset="utf-8"></script>
<script type="text/javascript" th:src="${#ContextPath()+'/static/x-admin/lib/layui/layui.js'}" charset="utf-8"></script> <script type="text/javascript" th:src="${#ContextPath()+'/static/x-admin/js/xadmin.js'}"></script>
<!-- kindeditor相关 -->
<link rel="stylesheet" th:href="${#ContextPath()+'/static/kindeditor/themes/default/default.css'}"/>
<link rel="stylesheet" th:href="${#ContextPath()+'/static/kindeditor/plugins/code/prettify.css'}"/>
<script charset="utf-8" th:src="${#ContextPath()+'/static/kindeditor/kindeditor-all.js'}"></script>
<script charset="utf-8" th:src="${#ContextPath()+'/static/kindeditor/lang/zh-CN.js'}"></script>
<script>
var editor;
editor = K.create('textarea[name="contentEditor"]', {
resizeType : 1,
allowPreviewEmoticons : false,
uploadJson : '/blogPicture/uploadPicture.html',
allowImageUpload : true,
pasteType : 0, //设置能否粘贴
items : [
'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
'insertunorderedlist', '|', 'emoticons', 'image', 'link','fullscreen']
});
});
</script>
<!-- 让IE8/9⽀持媒体查询,从⽽兼容栅格 -->
<!--[if lt IE 9]>
<script src="/html5shiv/r29/html5.min.js"></script>
<script src="/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="x-body layui-anim layui-anim-up">
<form class="layui-form">
<div class="layui-form-item">
<label for="L_email" class="layui-form-label">
<span class="x-red">*</span>博客标题
</label>
<div class="layui-input-inline">
<input type="text" id="L_blogtitle" name="blogtitle" lay-verify="required"
autocomplete="off" class="layui-input"/>
</div>
</div>
<div class="layui-form-item">
<label for="L_email" class="layui-form-label">
<span class="x-red">*</span>内容
<span class="x-red">*</span>内容
</label>
<div class="layui-input-inline">
<textarea name="contentEditor" id="test" cols="100" rows="8" ></textarea> </div>
</div>
<div class="layui-form-item">
<label for="L_repass" class="layui-form-label">
</label>
<button class="layui-btn" lay-filter="add" lay-submit="">
增加
</button>
</div>
</form>
</div>
</body>
<script>
/*<![CDATA[*/
layui.use(['form','layer'], function(){
$ = layui.jquery;
var form = layui.form
,
layer = layui.layer;
//监听提交
<('submit(add)', function(data){
var data = {
"blogtitle":$('[name="blogtitle"]').val(),
"content":editor.html()
}
//异步提交数据
$.post("/blog/doAddBlog.html",data,function(response){
if(response.success == true){
layer.msg("增加成功", {icon: 6},function () {
/
/ 获得frame索引
var index = FrameIndex(window.name);
//关闭当前frame
parent.layer.close(index);
// ⽗页⾯刷新
load();
});
}else{
layer.alert(response.msg);
}
});
return false;
});
});
/*]]>*/
</script>
</html>
界⾯如下:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论