SpringBoot 整合 UEditor 详细教程(一)| 整合教程
官方文档:http://fex.baidu.com/ueditor/.
项目地址:https://github.com/fex-team/ueditor.
官方源码zip包(UTF-8格式):ueditor-1.4.3.3.zip(github下载过慢)
- 链接:https://pan.baidu.com/s/1btFLz8PVXLot3CjL2qEiQQ
- 提取码:mja2
一、下载源码包
1.由于官网下载过慢,我在上面贴了百度云的下载链接(JSP、UTF-8版)
下载后方式项目的放入静态文件夹static
下:
2.引入 pom 依赖
<!-- UEditor -->
<dependency>
<groupId>com.gitee.qdbp.thirdparty</groupId>
<artifactId>ueditor</artifactId>
<version>1.4.3.3</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
3.改写以前jsp获取 config.json(上传相关配置) 文件的方法
注意:
-
图片不上传到云服务器的话需要做映射,可参考下一篇的踩坑文章
-
这里我写的上传方法在本地可以使用,然后由于部署到线上时出现config.json不能读取,就将config.json文件单独放出来了,具体可看代码;
-
还有一个问题就是上传图片,本地映射的方式在Linux服务器无法正常显示,搞了差不多一天,后面还是改成通过OSS上传到阿里云。(这里OSS上传代码就不贴了)
-
如果大家服务器改好了可告诉博主,博主进行实践和更新。
这里改写了原来百度编辑器的两个类:ActionEnter
和 ConfigManager
大致就是将里面的内容重写一遍(ActionEnterRewrite、ConfigManagerRewrite
),用于部署到linux环境时打印日志定位问题,大家可重写也可重写,主要用于定位每次获取config.json的获取路径
重写文件下载地址:
- 链接:https://pan.baidu.com/s/1JTyc_sHoQBlUCmhrXkN9rA
- 提取码:osfi
/**
* 描述: 百度编辑器引入
* 创建人: 慌途L
*/
@Slf4j
@RestController
public class UEditorController {
/**
* 获取config,json配置文件
*/
@RequestMapping("/ueditor/config")
public void getConfigInfo(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
String rootPath = "";
// 判断当前系统是否是Windows系统
if(isWindowsSystem()){
rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/ueditor/jsp";
} else {
// 将config.json文件放在jar包同级目录下
rootPath = "/usr/local/zgxsoft/yunapp-backend/service";
}
log.info("rootPath:{}", rootPath);
try {
response.setCharacterEncoding("UTF-8");
String exec = new ActionEnterRewrite(request, rootPath, "/config.json").exec();
log.info("exec:{}", UnicodeUtil.toString(exec));
PrintWriter writer = response.getWriter();
writer.write(exec);
writer.flush();
writer.close();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
/**
* UEditor 上传图片(单个或多个)---Windows使用(主要将config.json中的imageUrlPrefix改为本地地址)
* @return 返回提示信息
*/
@RequestMapping(value = "/ueditorUpload", method = RequestMethod.POST)
public Object upLoadImgToWindows(MultipartFile upfile){
Map<String,Object> map = new HashMap<String,Object>();
map.put("state", "上传失败");
if (Objects.isNull(upfile)) {
return map;
}
String oldName = upfile.getOriginalFilename();
String timeFileName = DateHelper.getDateStr(new Date());
// 判断当前系统是否是Windows系统
boolean system = isWindowsSystem();
String fileName = system ? FileUtils.upLoadFile(upfile,"F:/upload/admin/article/" + timeFileName)
: FileUtils.upLoadFile(upfile,imgUrl + "/" + timeFileName);
if (StringUtils.isNotBlank(fileName)) {
map.put("state", "SUCCESS");
// 图片url 浏览器不能直接访问项目外目录的图片等文件,需要做虚拟路径映射
// 这个路径的是在配置类里指定的映射到本地的绝对路径
if(system){
map.put("url", "/upload/admin/article/" + timeFileName + "/" + fileName);
} else {
map.put("url", "/" + mappingUrl + "/" + timeFileName + "/" + fileName);
}
//图片名称,这个会显示在输入框里
map.put("title", fileName);
//图片原名称
map.put("original", oldName);
//文件类型 .+后缀名
map.put("type", fileName.substring(fileName.lastIndexOf(".")));
//文件大小(字节数)
map.put("size", upfile.getSize());
}
log.info("map:{}", map);
return map;
}
/**
* 判断当前系统是否是Windows系统
* @return true:Windows系统,false:Linux系统
*/
private boolean isWindowsSystem(){
String property = System.getProperty("os.name").toLowerCase();
return property.contains("windows");
}
}
4.修改 ueditor.config.js 文件中的入口路径
这里是百度编辑器初始化时读取config.json
的方法路径
var server_url = window.location.protocol+"//"+window.location.hostname+":"+window.location.port;
5.测试文件 Demo.html:
(我这里用的是thymeleaf模板,有一些坑,就是在 script
标签中使用 UE.getEditor
时,需要使用下面的标签)
<script type="text/javascript" th:inline="none">
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:se="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 配置文件 -->
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
<!-- 编辑器源码文件 -->
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>
<!-- 中文 -->
<script type="text/javascript" charset="utf-8" src="/ueditor/lang/zh-cn/zh-cn.js"></script>
</head>
<body>
<div>
<script id="ueditorContent" name="content" style="min-height: 500px"></script>
</div>
</body>
<!-- 实例化编辑器 -->
<script type="text/javascript" th:inline="none">
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
console.log(UE.Editor.prototype.getActionUrl)
console.log(UE.Editor.prototype._bkGetActionUrl)
UE.Editor.prototype.getActionUrl = function(action) {
if (action === 'uploadimage') {
return '/ueditorUpload';// 此路径跟ueditor.config.js中的服务器统一请求接口路径一样,在同一个controller中
// return 'http://localhost:8090/upLoadImg';//自定义别的请求接口的需要加上IP和端口
} else {
return this._bkGetActionUrl.call(this, action);
}
}
var uee = UE.getEditor('ueditorContent', {
toolbars: [[
'fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'map', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
'preview', 'searchreplace', 'drafts'
]]
});
</script>
</html>
6.回显的时候需要使用以下代码:
UE.getEditor('ueditorContent').execCommand('insertHtml', content);
- ueditorContent:百度编辑器的ID
- content:回显的内容
7.测试上传图片(这里的单图和多图上传都是调用同一个接口,只是多图为多次调用)
下一篇为遇到的踩坑点:SpringBoot 整合 UEditor 详细教程(二)| 遇到的问题.
具体踩坑点:
- 1.自定义 toolbars 时出现 Could not parse as expression 异常
- 2.前端报错:请求后台配置项http错误,上传功能将不能正常使用
- 3.报错:"\u914d\u7f6e\u6587\u4ef6\u521d\u59cb\u5316\u5931\u8d25"(配置文件初始化失败)
- 4.配置上传图片,报错 : 无效的Action
- 5.注释多图上传里面的其他按钮
- 6.注释部分功能无法使用的代码
- 7.保存成功后无法正常显示文字和图片,或显示为空白
- 8.部署到服务器又出现了第3点的问题,加载不到config.json文件
参考网址:
- https://www.jianshu.com/p/241b2a401e32.
- https://www.jianshu.com/p/9548878c3e5b.
- https://blog.csdn.net/weixin_42132143/article/details/103783987.