文章目录
- 一、基础准备
- 1. 创建项目并引入依赖
- 2. 下载Ueditor源码
- 3. Java代码整合
- 4. 静态文件整合
- 二、静态页面+控制层
- 2.1. index.html
- 2.2. demo1.html
- 2.3. demo2.html
- 2.4. demo3.html
- 2.5. Controller
- 三、配置调整
- 3.1. 图片大小
- 3.2. 修改ueditor.config.js
- 3.3. 修改config.json文件
- 3.4. 修改BinaryUploader
- 3.5. 修改ConfigManage类
- 3.6. 设置图片在Ueditor中回显
一、基础准备
1. 创建项目并引入依赖
boot-ueditor
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.4</version><relativePath/> <!-- lookup parent from repository --></parent><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20190722</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>
2. 下载Ueditor源码
下载地址:https://github.com/fex-team/ueditor/tree/dev-2.0.0
3. Java代码整合
将ueditor-dev-2.0.0版本\ueditor\jsp\src
下的com文件夹整体复制到项目Java目录下面
4. 静态文件整合
- ①把
ueditor
整个文件夹复制到static目录下面 - ②把
ueditor\jsp\config.json
复制到ueditor的根目录下面 - ③在resources目录下面创建js文件夹存放
jquery2.1.3.min.js
二、静态页面+控制层
在resources
目录下面创建templates
2.1. index.html
<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>完整demo</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script><!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--><!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--><script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script><style type="text/css">div{width:100%;}</style>
</head>
<body>
<div><h1>完整demo</h1><script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
</div>
<div id="btns"><div><button onclick="getAllHtml()">获得整个html的内容</button><button onclick="getContent()">获得内容</button><button onclick="setContent()">写入内容</button><button onclick="setContent(true)">追加内容</button><button onclick="getContentTxt()">获得纯文本</button><button onclick="getPlainTxt()">获得带格式的纯文本</button><button onclick="hasContent()">判断是否有内容</button><button onclick="setFocus()">使编辑器获得焦点</button><button onmousedown="isFocus(event)">编辑器是否获得焦点</button><button onmousedown="setblur(event)" >编辑器失去焦点</button></div><div><button onclick="getText()">获得当前选中的文本</button><button onclick="insertHtml()">插入给定的内容</button><button id="enable" onclick="setEnabled()">可以编辑</button><button onclick="setDisabled()">不可编辑</button><button onclick=" UE.getEditor('editor').setHide()">隐藏编辑器</button><button onclick=" UE.getEditor('editor').setShow()">显示编辑器</button><button onclick=" UE.getEditor('editor').setHeight(300)">设置高度为300默认关闭了自动长高</button></div><div><button onclick="getLocalData()" >获取草稿箱内容</button><button onclick="clearLocalData()" >清空草稿箱</button></div></div>
<div><button onclick="createEditor()">创建编辑器</button><button onclick="deleteEditor()">删除编辑器</button>
</div><script type="text/javascript">//实例化编辑器//建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例var ue = UE.getEditor('editor');function isFocus(e){alert(UE.getEditor('editor').isFocus());UE.dom.domUtils.preventDefault(e)}function setblur(e){UE.getEditor('editor').blur();UE.dom.domUtils.preventDefault(e)}function insertHtml() {var value = prompt('插入html代码', '');UE.getEditor('editor').execCommand('insertHtml', value)}function createEditor() {enableBtn();UE.getEditor('editor');}function getAllHtml() {alert(UE.getEditor('editor').getAllHtml())}function getContent() {var arr = [];arr.push("使用editor.getContent()方法可以获得编辑器的内容");arr.push("内容为:");arr.push(UE.getEditor('editor').getContent());alert(arr.join("\n"));}function getPlainTxt() {var arr = [];arr.push("使用editor.getPlainTxt()方法可以获得编辑器的带格式的纯文本内容");arr.push("内容为:");arr.push(UE.getEditor('editor').getPlainTxt());alert(arr.join('\n'))}function setContent(isAppendTo) {var arr = [];arr.push("使用editor.setContent('欢迎使用ueditor')方法可以设置编辑器的内容");UE.getEditor('editor').setContent('欢迎使用ueditor', isAppendTo);alert(arr.join("\n"));}function setDisabled() {UE.getEditor('editor').setDisabled('fullscreen');disableBtn("enable");}function setEnabled() {UE.getEditor('editor').setEnabled();enableBtn();}function getText() {//当你点击按钮时编辑区域已经失去了焦点,如果直接用getText将不会得到内容,所以要在选回来,然后取得内容var range = UE.getEditor('editor').selection.getRange();range.select();var txt = UE.getEditor('editor').selection.getText();alert(txt)}function getContentTxt() {var arr = [];arr.push("使用editor.getContentTxt()方法可以获得编辑器的纯文本内容");arr.push("编辑器的纯文本内容为:");arr.push(UE.getEditor('editor').getContentTxt());alert(arr.join("\n"));}function hasContent() {var arr = [];arr.push("使用editor.hasContents()方法判断编辑器里是否有内容");arr.push("判断结果为:");arr.push(UE.getEditor('editor').hasContents());alert(arr.join("\n"));}function setFocus() {UE.getEditor('editor').focus();}function deleteEditor() {disableBtn();UE.getEditor('editor').destroy();}function disableBtn(str) {var div = document.getElementById('btns');var btns = UE.dom.domUtils.getElementsByTagName(div, "button");for (var i = 0, btn; btn = btns[i++];) {if (btn.id == str) {UE.dom.domUtils.removeAttributes(btn, ["disabled"]);} else {btn.setAttribute("disabled", "true");}}}function enableBtn() {var div = document.getElementById('btns');var btns = UE.dom.domUtils.getElementsByTagName(div, "button");for (var i = 0, btn; btn = btns[i++];) {UE.dom.domUtils.removeAttributes(btn, ["disabled"]);}}function getLocalData () {alert(UE.getEditor('editor').execCommand( "getlocaldata" ));}function clearLocalData () {UE.getEditor('editor').execCommand( "clearlocaldata" );alert("已清空草稿箱")}
</script>
</body>
</html>
2.2. demo1.html
<html xmlns:th="http://www.thymeleaf.org">
<head><title>UEditor Demo</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script><!-- ueditor start --><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script><!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--><!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--><script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script><!-- ueditor end --></head>
<body><div><h1>完整demo</h1><textarea id="editor" type="text/plain" style="width:95%;height:500px;"></textarea></div><button onclick="getContent()">获得内容</button><script type="text/javascript">//实例化编辑器//建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例let ue = UE.getEditor('editor');function getContent() {let arr = [];arr.push(ue.getContent());$.post("ueditor/d1",arr.join("\n"));}</script>
</body>
</html>
2.3. demo2.html
<html xmlns:th="http://www.thymeleaf.org">
<head><title>UEditor Demo</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script><!-- ueditor start --><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script><!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--><!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--><script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script><!-- ueditor end -->
</head>
<body><div><h1>完整demo</h1><textarea id="editor" type="text/plain" style="width:95%;height:500px;"></textarea></div><button onclick="getContent()">获得内容</button><script type="text/javascript">//实例化编辑器let ue = UE.getEditor('editor');function getContent() {let arr = [];arr.push(ue.getContent());$.post("ueditor/d2","data="+arr.join("\n"));}</script>
</body>
</html>
2.4. demo3.html
<html xmlns:th="http://www.thymeleaf.org">
<head><title>UEditor Demo</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8"/><script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script><!-- ueditor start --><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script><!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败--><!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文--><script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script><script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script><!-- ueditor end -->
</head>
<body><form th:action="@{ueditor/d3}">姓名:<input type="text" name="name" id="name"><br>简介:<textarea id="info" type="text/plain" style="width:95%;height:200px;"></textarea><input type="submit" value="提交"></form><script type="text/javascript">//实例化编辑器let ue = UE.getEditor('info');</script>
</body>
</html>
2.5. Controller
DispatcherController
package com.baidu.ueditor.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class DispatcherController {@RequestMapping("/index")public String index() {return "index";}@RequestMapping("/demo1")public String demo1() {return "demo1";}@RequestMapping("/demo2")public String demo2() {return "demo2";}@RequestMapping("/demo3")public String demo3() {return "demo3";}
}
UEditorController
package com.baidu.ueditor.controller;import com.baidu.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;@Controller
@RequestMapping("/ueditor")
public class UEditorController {@RequestMapping(value = "/config")public void config(HttpServletRequest request, HttpServletResponse response) {response.setContentType("application/json");String rootPath = request.getSession().getServletContext().getRealPath("/");try {String exec = new ActionEnter(request, rootPath).exec();PrintWriter writer = response.getWriter();writer.write(exec);writer.flush();writer.close();} catch (IOException e) {e.printStackTrace();}}///@ResponseBody@RequestMapping("/d1")public void demo1(HttpServletRequest request) throws IOException {ServletInputStream is = request.getInputStream();String str = inputStream2String(is, "UTF-8");System.out.println("用户在UEditor中输入的内容是:" + str);}public static String inputStream2String(InputStream is, String encode) {String str = "";try {if (encode == null || encode.equals("")) {encode = "utf-8";// 默认以utf-8形式}BufferedReader br = new BufferedReader(new InputStreamReader(is, encode));StringBuffer sb = new StringBuffer();while ((str = br.readLine()) != null) {sb.append(str).append("\n");}return sb.toString();} catch (IOException e) {e.printStackTrace();}return str;}@ResponseBody@RequestMapping("/d2")public void demo2(HttpServletRequest request) throws IOException {String data = request.getParameter("data");System.out.println(data);}@ResponseBody@RequestMapping("/d3")public void demo3(String name,String editorValue) throws IOException {System.out.println("doGet");System.out.println(name);System.out.println(editorValue);}
}
三、配置调整
3.1. 图片大小
当用户上传的图片太大时,为了不让Ueditor不出现水平滚动轴,可以修改ueditor.all.js文件以及ueditor.all.mini.js文件
3.2. 修改ueditor.config.js
修改ueditor.config.js文件,在其中指定Ueditor请求的服务器端的路径:
3.3. 修改config.json文件
修改config.json文件,为其添加一个表示上传资料基本路径的变量basePath
3.4. 修改BinaryUploader
修改BinaryUploader的save()方法的代码如下
public static final State save(HttpServletRequest request,Map<String, Object> conf) {// FileItemStream fileStream = null;// boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;if (!ServletFileUpload.isMultipartContent(request)) {return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);}// ServletFileUpload upload = new ServletFileUpload(// new DiskFileItemFactory());//// if ( isAjaxUpload ) {// upload.setHeaderEncoding( "UTF-8" );// }try {// FileItemIterator iterator = upload.getItemIterator(request);//// while (iterator.hasNext()) {// fileStream = iterator.next();//// if (!fileStream.isFormField())// break;// fileStream = null;// }//// if (fileStream == null) {// return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);// }MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());if(multipartFile==null){return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);}String savePath = (String) conf.get("savePath");//String originFileName = fileStream.getName();String originFileName = multipartFile.getOriginalFilename();String suffix = FileType.getSuffixByFilename(originFileName);originFileName = originFileName.substring(0,originFileName.length() - suffix.length());savePath = savePath + suffix;long maxSize = ((Long) conf.get("maxSize")).longValue();if (!validType(suffix, (String[]) conf.get("allowFiles"))) {return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);}savePath = PathFormat.parse(savePath, originFileName);//String physicalPath = (String) conf.get("rootPath") + savePath;String basePath=(String) conf.get("basePath");String physicalPath = basePath + savePath;//InputStream is = fileStream.openStream();InputStream is = multipartFile.getInputStream();State storageState = StorageManager.saveFileByInputStream(is,physicalPath, maxSize);is.close();if (storageState.isSuccess()) {storageState.putInfo("url", PathFormat.format(savePath));storageState.putInfo("type", suffix);storageState.putInfo("original", originFileName + suffix);}return storageState;// } catch (FileUploadException e) {// return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);} catch (IOException e) {}return new BaseState(false, AppInfo.IO_ERROR);}
3.5. 修改ConfigManage类
- 修改成员变量configFileName的值为config.json的路径值:
private static final String configFileName = "static/ueditor/config.json";
- 在getConfig()方法的return语句之前添加如下代码:
//将basePath塞进confconf.put("basePath", this.jsonConfig.getString("basePath"));conf.put("savePath", savePath);conf.put("rootPath", this.rootPath);
- 修改initEnv()方法
为了让项目在打包后能正常够上传文件/图片,修改initEnv()方法用Class类的getResourceAsStream()来读取文件
private void initEnv() throws FileNotFoundException, IOException {File file = new File(this.originalPath);if (!file.isAbsolute()) {file = new File(file.getAbsolutePath());}this.parentPath = file.getParent();//String configContent = this.readFile(this.getConfigPath());String configContent = this.filter(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(configFileName)));try {JSONObject jsonConfig = new JSONObject(configContent);this.jsonConfig = jsonConfig;} catch (Exception e) {this.jsonConfig = null;}
}
- 修改getConfigPath()方法的代码如下:
private String getConfigPath() {try {//获取classpath下的config.json路径return this.getClass().getClassLoader().getResource(configFileName).toURI().getPath();} catch (URISyntaxException e) {return this.parentPath + File.separator + ConfigManager.configFileName;}
}
3.6. 设置图片在Ueditor中回显
因为我们把图片存在E盘了,而spring并没有对E盘目录进行映射。只有按如下所示在application.properties文件加入路径映射,上传成功的图片在Ueditor中才才能回显:
spring:servlet:#设置SpringBoot内置tomcat允许上传图片的大小multipart:max-file-size: 100MBmax-request-size: 1000MB#路径映射,Ueditor上传图片成功后回显用resources:static-locations: classpath:static/,file:static/,file:D:/ueditor