百度UEditor富文本插件的使用


這個富文本還是功能挺全的.

官方文檔地址

下載地址

常用接口

較完整代碼倉庫

UEditor下載后直接運行即可訪問,但在上傳文件時需要單獨再做配置.

[很詳細的SpringBoot整合UEditor教程]

可選的依賴文件,本案例不采用:

       <dependency>
            <groupId>net.mingsoft</groupId>
            <artifactId>ms-ueditor</artifactId>
            <version>1.0.2</version>
        </dependency>

 

官方的demo就不多說了.

下面是我設置的富文本,其中可以進行富文本大小的拉縮.當提交數據時,使用 UE.getEditor('container').getContent() 即可獲取富文本內容.

如果是發表新聞的話,可以把標題,作者等input內容放入form中,使用jquery.serializejson.js獲取json數據,並加上content富文本內容傳遞給后端.

前端demo.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>ueditor demo</title>

    <!--配置文件-->
    <script type="text/javascript" src="ueditor.config.js"></script>
    <!--編輯器源碼文件-->
    <script type="text/javascript" src="/ueditor/ueditor.all.js"></script>
    <script src="/ueditor/ueditor.parse.min.js"></script>
    <script src="/js/jquery-3.1.0.min.js"></script>
    <script src="/js/jquery.serializejson.js"></script>

</head>
<body>
    <!--加載編輯器的容器-->
    <script id="container" name="content" type="text/plain"></script>

<button id="formBtn">提交</button>



<!--實例化編輯器-->
<script type="text/javascript">
    var ue = UE.getEditor('container',{
        //工具欄上的所有的功能按鈕和下拉框,可以在new編輯器的實例時選擇自己需要的從新定義
        autoHeightEnabled: true, //設置自動長高
        scaleEnabled: true, //是否可以拉伸長高,默認true(當開啟時,自動長高失效)
        autoFloatEnabled: false,  //自動浮動,false能適應全部寬度,是否保持toolbar的位置不動,默認true
        initialContent: '請在這里輸入要編輯的內容', //富文本提示內容
        autoClearinitialContent: true, //聚焦富文本后清空提示內容
        enableAutoSave: true, //啟用自動保存
        imageScaleEnabled: true, //啟動圖片拉伸縮放
        pasteplain: true, //啟用純文本粘貼
        allHtmlEnabled: false, //提交到后台的數據是否包含整個html字符串
        autoTransWordToList: true, // [默認值:false] //禁止word中粘貼進來的列表自動變成列表標簽
        enableContextMenu: true, //右鍵功能菜單
        maximumWords: 10001, //允許的最大字符數
        tabSize: 4, //點擊tab鍵時移動的距離,tabSize倍數,tabNode什么字符做為單位
        tabNode: '&nbsp;', //tab使用的單位,空格
        tableDragable: true, //表格是否可以拖拽
        sourceEditor: "codemirror",  //源碼的查看方式,codemirror是代碼高亮,textarea是文本框,默認是codemirror,注意默認codemirror只能在ie8+和非ie中使用

    });
</script>


<script>

    $("#formBtn").click(editorSubmit);

    function editorSubmit(){
        // alert("content:"+(UE.getEditor('editor').getContent()));
        $.ajax({
            url:"/editorData",
            type:"POST",
            // data:$("#editor").serializeJSON(),
            data:{"content":UE.getEditor('container').getContent()},
            dataType:"json",
            success:function(data){
                alert(data);
            }
        });
    }

</script>


</body>
</html>

對應上面前端的接口

package com.tansuo365.test1.controller.ueditor;

import com.tansuo365.test1.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

@RequestMapping("")
@Controller
public class UEditorController {

    @RequestMapping("/ueditor")
    private String ueditor() {
        return "/news/index";
    }

    @RequestMapping("/ueditorDemo")
    private String ueditorDemo() {
        return "/news/demo";
    }

    @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();
        }

    }

    //TODO
    @ResponseBody
    @RequestMapping("editorData")
    public Integer testEditor(@RequestParam("content") String content) {
        System.out.println("content:" + content);
        return 1;
    }
}

 

官方demo: 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.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor.all.js}"> </script>
    <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
    <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" th:src="@{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>

 

在java端的application.properties或yml中加入:

#ueditor文件上傳路徑
web.upload-path=E:/   <<按需改為linux路徑
spring.mvc.static-path-pattern=/**
#靜態資源,ueditor文件上傳路徑
spring.resources.static-locations=classpath:/static/,file:${web.upload-path}

同時在ueditor.json或原本的config.json中需要更改basePath和web.upload-path一致(圖片/文件上傳路徑)

其它比較重要的如ConfigManager,3個js文件(ueditor.all.js,ueditor.config.js,ueditor.parse.js),一個ueditor.json文件.

"basePath":"/www/server/apache-tomcat-8.5.32/webapps/ROOT/images/",/* 上傳文件的基本路徑 */









免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM