springboot整合ueditor(主要講上傳功能的實現)

前言

本文主要寫的是:springboot下ueditor上傳功能的實現及遇到的一些問題的處理

 

整體項目結構展示

 

Springboot整合ueditor及上傳功能實現的具體步驟

1、下載ueditor-1.4.3.3

這個在官網下載就行,不過貌似utf-8版本的沒有資源了,源碼版的下了幾次都中斷了,最終我是從第三方下的

2、新建一個測試頁面

ueditor的根目錄下有一個index.html,用它就行,源碼如下

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title>完整demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <!-- 將config.json放在保存文件的根目錄位置 -->
    <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.js"> </script>
</head>
<body>
<div>
    <h1>UEditor演示</h1>
    <script id="editor" type="text/plain" style="width:100%;height:330px;"></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>

3、引入上傳所需的jar包

<dependency>
	<groupId>com.gitee.qdbp.thirdparty</groupId>
	<artifactId>ueditor</artifactId>
	<version>1.4.3.3</version>
</dependency>
<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
	<groupId>commons-fileupload</groupId>
	<artifactId>commons-fileupload</artifactId>
	<version>1.3.1</version>
</dependency>
<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.5</version>
	<scope>compile</scope>
</dependency>
<dependency>
	<groupId>org.json</groupId>
	<artifactId>json</artifactId>
</dependency>

4、新建上傳文件保存目錄文件夾,如下

其中的config.json是從ueditor-1.4.3.3的文件夾裏拷過來,因爲我發現默認上傳文件路徑就是config.json所在目錄,而且springboot下我試了配置imagePathFormat並沒有什麼用。

5、新建UeditorController

用於讀取ueditor.json配置文件,同時實現上傳方法(當然這裏我們直接使用了ueditor.jar的上傳,因此顯得很簡單,但如果要我們自己寫那就有一堆代碼量了)

import com.baidu.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 百度富文本編輯器
 * 描述1:config.json中配置的如圖片大小限制(imageMaxSize)文件類型等在頁面js中已經驗證過了,後臺不需要在處理
 * 描述2:使用ueditor.jar的話就不需要自己
 * 描述3:config.json中imageUrlPrefix配置舉例:"imageUrlPrefix": "/fileupload/ueditor"
 * 描述3:config.json中imagePathFormat配置舉例:"imagePathFormat": "/image/{yyyy}{mm}{dd}/{time}{rand:6}"
 * 描述4:imageUrlPrefix + imagePathFormat 爲上傳文件的訪問路徑
 *
 * zkh
 * 2019年11月14日 9:09
 */
@Controller
public class UeditorController {

    // /ueditor/jsp/config.json文件所在的父目錄,上傳文件默認根目錄爲config.json文件所在目錄
    private String configJsonParentPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/fileupload/ueditor";

    /**
     * UEditor初始化時會以get方式請求serverUrl地址,並且需要在action=config時返回UEditor配置文件信息
     * 描述:使用ueditor.jar包中的ActionEnter的話,就不需要自己再去實現其上傳功能,因爲ActionEnter已經幫我們實現了
     */
    @RequestMapping("ueditor")
    public void getEditorConfig(HttpServletRequest request, HttpServletResponse response, String action) {
        response.setContentType("application/json");
        try {
            String exec = new ActionEnter(request, configJsonParentPath).exec();
            if(action!=null && (action.equals("listfile") || action.equals("listimage"))) {
                exec = exec.replace(configJsonParentPath.substring(1), "/");
            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

注意看註釋

6、接着,我們需要將ueditor.config.js中的serverUrl配置爲我們在第5步的那個controller,如下

7、最後還要在config.json中配置下我們上傳的具體細節,下面以圖片上傳爲例

/* 上傳圖片配置項 */
    "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱(舉例:http://localhost:8080/ueditor?action=uploadimage) */
    "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
    "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
    "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
    "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
    "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
    /* imageUrlPrefix + imagePathFormat 爲當前文件的訪問路徑 */
    "imageUrlPrefix": "/fileupload/ueditor", /* 圖片訪問路徑前綴 */
    /* imagePathFormat默認以當前config.json所在的目錄爲根目錄 */
    "imagePathFormat": "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* (注意:默認以當前config.json所在的目錄爲根目錄)上傳保存路徑,可以自定義保存路徑和文件名格式 */
                                /* {filename} 會替換成原文件名,配置這項需要注意中文亂碼問題 */
                                /* {rand:6} 會替換成隨機數,後面的數字是隨機數的位數 */
                                /* {time} 會替換成時間戳 */
                                /* {yyyy} 會替換成四位年份 */
                                /* {yy} 會替換成兩位年份 */
                                /* {mm} 會替換成兩位月份 */
                                /* {dd} 會替換成兩位日期 */
                                /* {hh} 會替換成兩位小時 */
                                /* {ii} 會替換成兩位分鐘 */
                                /* {ss} 會替換成兩位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具請體看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */

這裏我們需要關注重點理解的是 imageUrlPrefix 、imagePathFormat

1) 域名 + imageUrlPrefix + imagePathFormat 爲當前文件的訪問路徑;

2)imageUrlPrefix是圖片訪問路徑前綴,例如:http://localhost:8080/fileupload/ueditor,imageUrlPrefix就是其中的“/fileupload/ueditor”;

3)imagePathFormat是以imageUrlPrefix爲根路徑的文件存放的具體路徑,例如:http://localhost:8080/fileupload/ueditor/image/20190202/121222.jpg,imagePathFormat就是其中的“/image/20190202/121222.jpg”;

4)剩下其他參數就很明顯了。

7、可能會遇到的問題

1、明明配置的文件最大爲2048000,但是文件只有1M多點後臺報錯了?

解決:這是因爲默認開啓了springboot的上傳,在application.properties中 spring.servlet.multipart.enabled=false 就可以了,或者也可以跳下它的默認最大值 spring.servlet.multipart.max-file-size=1MB,具體如下圖:

2、明明修改了imagePathFormat,單還是保存在了原始的路徑下?

解決:直接將config.json文件放到了我想保存文件的位置即可。

3、在線管理圖片無法顯示?

解決:在我們上面的UeditorController中其實已經解決了,就是當action=listfile或者action=listimage時將new ActionEnter(request, configJsonParentPath).exec()得到的字符串中的configJsonParentPath路徑替換爲空字符串即可,如下

 

最後啓動服務,打開http://localhost:8080/ueditor/index.html頁面測試,效果如下圖:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章