文章目錄
- ??3.1. 圖片大小??
- ??3.2. 修改ueditor.config.js??
- ??3.3. 修改config.json文件??
- ??3.4. 修改BinaryUploader??
- ??3.5. 修改ConfigManage類??
- ??3.6. 設(shè)置圖片在Ueditor中回顯??
一、基礎(chǔ)準備
1. 創(chuàng)建項目并引入依賴
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版本ueditorjspsrc?
?下的com文件夾整體復(fù)制到項目Java目錄下面
4. 靜態(tài)文件整合
- ①把?
?ueditor?
?整個文件夾復(fù)制到static目錄下面 - ②把?
?ueditorjspconfig.json?
?復(fù)制到ueditor的根目錄下面 - ③在resources目錄下面創(chuàng)建js文件夾存放?
?jquery2.1.3.min.js?
?
二、靜態(tài)頁面+控制層
在??resources?
??目錄下面創(chuàng)建??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下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
<!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
<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的內(nèi)容</button>
<button onclick="getContent()">獲得內(nèi)容</button>
<button onclick="setContent()">寫入內(nèi)容</button>
<button onclick="setContent(true)">追加內(nèi)容</button>
<button onclick="getContentTxt()">獲得純文本</button>
<button onclick="getPlainTxt()">獲得帶格式的純文本</button>
<button onclick="hasContent()">判斷是否有內(nèi)容</button>
<button onclick="setFocus()">使編輯器獲得焦點</button>
<button onmousedown="isFocus(event)">編輯器是否獲得焦點</button>
<button onmousedown="setblur(event)" >編輯器失去焦點</button>
</div>
<div>
<button onclick="getText()">獲得當前選中的文本</button>
<button onclick="insertHtml()">插入給定的內(nèi)容</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)">設(shè)置高度為300默認關(guān)閉了自動長高</button>
</div>
<div>
<button onclick="getLocalData()" >獲取草稿箱內(nèi)容</button>
<button onclick="clearLocalData()" >清空草稿箱</button>
</div>
</div>
<div>
<button onclick="createEditor()">
創(chuàng)建編輯器</button>
<button onclick="deleteEditor()">
刪除編輯器</button>
</div>
<script type="text/javascript">
//實例化編輯器
//建議使用工廠方法getEditor創(chuàng)建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調(diào)用UE.getEditor('editor')就能拿到相關(guān)的實例
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()方法可以獲得編輯器的內(nèi)容");
arr.push("內(nèi)容為:");
arr.push(UE.getEditor('editor').getContent());
alert(arr.join(" "));
}
function getPlainTxt() {
var arr = [];
arr.push("使用editor.getPlainTxt()方法可以獲得編輯器的帶格式的純文本內(nèi)容");
arr.push("內(nèi)容為:");
arr.push(UE.getEditor('editor').getPlainTxt());
alert(arr.join(' '))
}
function setContent(isAppendTo) {
var arr = [];
arr.push("使用editor.setContent('歡迎使用ueditor')方法可以設(shè)置編輯器的內(nèi)容");
UE.getEditor('editor').setContent('歡迎使用ueditor', isAppendTo);
alert(arr.join(" "));
}
function setDisabled() {
UE.getEditor('editor').setDisabled('fullscreen');
disableBtn("enable");
}
function setEnabled() {
UE.getEditor('editor').setEnabled();
enableBtn();
}
function getText() {
//當你點擊按鈕時編輯區(qū)域已經(jīng)失去了焦點,如果直接用getText將不會得到內(nèi)容,所以要在選回來,然后取得內(nèi)容
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()方法可以獲得編輯器的純文本內(nèi)容");
arr.push("編輯器的純文本內(nèi)容為:");
arr.push(UE.getEditor('editor').getContentTxt());
alert(arr.join(" "));
}
function hasContent() {
var arr = [];
arr.push("使用editor.hasContents()方法判斷編輯器里是否有內(nèi)容");
arr.push("判斷結(jié)果為:");
arr.push(UE.getEditor('editor').hasContents());
alert(arr.join(" "));
}
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下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
<!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
<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()">獲得內(nèi)容</button>
<script type="text/javascript">
//實例化編輯器
//建議使用工廠方法getEditor創(chuàng)建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調(diào)用UE.getEditor('editor')就能拿到相關(guān)的實例
let ue = UE.getEditor('editor');
function getContent() {
let arr = [];
arr.push(ue.getContent());
$.post("ueditor/d1",arr.join(" "));
}
</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下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
<!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
<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()">獲得內(nèi)容</button>
<script type="text/javascript">
//實例化編輯器
let ue = UE.getEditor('editor');
function getContent() {
let arr = [];
arr.push(ue.getContent());
$.post("ueditor/d2","data="+arr.join(" "));
}
</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下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
<!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
<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中輸入的內(nèi)容是:" + 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(" ");
}
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);
}
}
三、配置調(diào)整
3.1. 圖片大小
當用戶上傳的圖片太大時,為了不讓Ueditor不出現(xiàn)水平滾動軸,可以修改ueditor.all.js文件以及ueditor.all.mini.js文件
3.2. 修改ueditor.config.js
修改ueditor.config.js文件,在其中指定Ueditor請求的服務(wù)器端的路徑:
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", 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. 設(shè)置圖片在Ueditor中回顯
因為我們把圖片存在E盤了,而spring并沒有對E盤目錄進行映射。只有按如下所示在application.properties文件加入路徑映射,上傳成功的圖片在Ueditor中才才能回顯:
spring:
servlet:
#設(shè)置SpringBoot內(nèi)置tomcat允許上傳圖片的大小
multipart:
max-file-size: 100MB
max-request-size: 1000MB
#路徑映射,Ueditor上傳圖片成功后回顯用
本文摘自 :https://blog.51cto.com/g