开发喵星球

集成ueditor实现富文本编辑器增强(137)

UEditor是由百度前端研发部开发所见即所得富文本web编辑器,具有轻量、可定制、注重用户体验等特点。可以很好的满足国内用户的需求。

1、下载UEditor前端插件

链接: https://pan.baidu.com/s/13JVC9jm-Dp9PfHdDDylLCQ
提取码: y9jt

uoyi/集成ueditor实现富文本编辑器增强.zip
ruoyi-admin\src\main\resources\static\ajax\libs\ueditor 复制插件文件到自己的项目

2、ruoyi-admin\include.html添加ueditor

<!-- ueditor富文本编辑器插件 -->
<div th:fragment="ueditor-js">
    <script th:src="@{/ajax/libs/ueditor/ueditor.config.js}"></script>
    <script th:src="@{/ajax/libs/ueditor/ueditor.all.min.js}"></script>
    <script th:src="@{/ajax/libs/ueditor/lang/zh-cn/zh-cn.js}"></script>
</div>

3、修改通知公告相关页面

修改 templates\system\notice\add.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增通知公告')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-notice-add">
            <div class="form-group">    
                <label class="col-sm-2 control-label is-required">公告标题:</label>
                <div class="col-sm-10">
                    <input id="noticeTitle" name="noticeTitle" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">公告类型:</label>
                <div class="col-sm-10">
                    <select name="noticeType" class="form-control m-b" th:with="type={@dict.getType('sys_notice_type')}">
                        <option th:each="dict :{type}" th:text="{dict.dictLabel}" th:value="{dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-2 control-label">公告内容:</label>
                <div class="col-sm-10">
                    <script id="editor" name="noticeContent" type="text/plain" style="height: 300px;"></script>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">公告状态:</label>
                <div class="col-sm-10">
                    <div class="radio-box" th:each="dict : {@dict.getType('sys_notice_status')}">
                        <input type="radio" th:id="{dict.dictCode}" name="status" th:value="{dict.dictValue}" th:checked="{dict.default}">
                        <label th:for="{dict.dictCode}" th:text="{dict.dictLabel}"></label>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: ueditor-js" />
    <script type="text/javascript">
        var prefix = ctx + "system/notice";

        var ue = UE.getEditor('editor');

        function getContentTxt() {
            return UE.getEditor('editor').getContentTxt();
        }

        ("#form-notice-add").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if (.validate.form()) {
                var text = getContentTxt();
                if (text == '' || text.length == 0) {
                    .modal.alertWarning("请输入公告内容!");
                    return;
                }.operate.save(prefix + "/add", $('#form-notice-add').serialize());
            }
        }
    </script>
</body>
</html>

修改 templates\system\notice\edit.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改通知公告')" />
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-notice-edit" th:object="{notice}">
            <input id="noticeId" name="noticeId" th:field="*{noticeId}"  type="hidden">
            <div class="form-group">                   <label class="col-sm-2 control-label is-required">公告标题:</label>
                <div class="col-sm-10">
                    <input id="noticeTitle" name="noticeTitle" th:field="*{noticeTitle}" class="form-control" type="text" required>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">公告类型:</label>
                <div class="col-sm-10">
                    <select name="noticeType" class="form-control m-b" th:with="type={@dict.getType('sys_notice_type')}">
                        <option th:each="dict : {type}" th:text="{dict.dictLabel}" th:value="{dict.dictValue}" th:field="*{noticeType}"></option>
                    </select>
                </div>
            </div>
            <div class="form-group">                   <label class="col-sm-2 control-label">公告内容:</label>
                <div class="col-sm-10">
                    <script id="editor" name="noticeContent" type="text/plain" style="height: 300px;"></script>
                    <textarea id="noticeContent" style="display: none;">[[*{noticeContent}]]</textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">公告状态:</label>
                <div class="col-sm-10">
                    <div class="radio-box" th:each="dict :{@dict.getType('sys_notice_status')}">
                        <input type="radio" th:id="{dict.dictCode}" name="status" th:value="{dict.dictValue}" th:field="*{status}">
                        <label th:for="{dict.dictCode}" th:text="{dict.dictLabel}"></label>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: ueditor-js" />
    <script type="text/javascript">
        var prefix = ctx + "system/notice";

        (function () {
            var text =("#noticeContent").text();
            var ue = UE.getEditor('editor');
            ue.ready(function () {
                ue.setContent(text);
            });
        })

        function getContentTxt() {
            return UE.getEditor('editor').getContentTxt();
        }

        ("#form-notice-edit").validate({
            focusCleanup: true
        });

        function submitHandler() {
            if (.validate.form()) {
                var text = getContentTxt();
                if (text == '' || text.length == 0) {
                    .modal.alertWarning("请输入通知内容!");
                    return;
                }.operate.save(prefix + "/edit", $('#form-notice-edit').serialize());
            }
        }
    </script>
</body>
</html>

4、添加配置文件到ruoyi-admin\src\main\resources

新增 ueditor-config.json

/* 前后端通信相关的配置,注释只允许使用多行方式 */
{
    /* 上传图片配置项 */
    "imageActionName": "uploadimage", /* 执行上传图片的action名称 */
    "imageFieldName": "upfile", /* 提交的图片表单名称 */
    "imageMaxSize": 2048000, /* 上传大小限制,单位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上传图片格式显示 */
    "imageCompressEnable": true, /* 是否压缩图片,默认是true */
    "imageCompressBorder": 1600, /* 图片压缩最长边限制 */
    "imageInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageUrlPrefix": "", /* 图片访问路径前缀 */
    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                                /* {filename} 会替换成原文件名,配置这项需要注意中文乱码问题 */
                                /* {rand:6} 会替换成随机数,后面的数字是随机数的位数 */
                                /* {time} 会替换成时间戳 */
                                /* {yyyy} 会替换成四位年份 */
                                /* {yy} 会替换成两位年份 */
                                /* {mm} 会替换成两位月份 */
                                /* {dd} 会替换成两位日期 */
                                /* {hh} 会替换成两位小时 */
                                /* {ii} 会替换成两位分钟 */
                                /* {ss} 会替换成两位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 涂鸦图片上传配置项 */
    "scrawlActionName": "uploadscrawl", /* 执行上传涂鸦的action名称 */
    "scrawlFieldName": "upfile", /* 提交的图片表单名称 */
    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上传大小限制,单位B */
    "scrawlUrlPrefix": "", /* 图片访问路径前缀 */
    "scrawlInsertAlign": "none",

    /* 截图工具上传 */
    "snapscreenActionName": "uploadimage", /* 执行上传截图的action名称 */
    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "snapscreenUrlPrefix": "", /* 图片访问路径前缀 */
    "snapscreenInsertAlign": "none", /* 插入的图片浮动方式 */

    /* 抓取远程图片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 执行抓取远程图片的action名称 */
    "catcherFieldName": "source", /* 提交的图片列表表单名称 */
    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "catcherUrlPrefix": "", /* 图片访问路径前缀 */
    "catcherMaxSize": 2048000, /* 上传大小限制,单位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取图片格式显示 */

    /* 上传视频配置 */
    "videoActionName": "uploadvideo", /* 执行上传视频的action名称 */
    "videoFieldName": "upfile", /* 提交的视频表单名称 */
    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "videoUrlPrefix": "", /* 视频访问路径前缀 */
    "videoMaxSize": 102400000, /* 上传大小限制,单位B,默认100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上传视频格式显示 */

    /* 上传文件配置 */
    "fileActionName": "uploadfile", /* controller里,执行上传视频的action名称 */
    "fileFieldName": "upfile", /* 提交的文件表单名称 */
    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
    "fileUrlPrefix": "", /* 文件访问路径前缀 */
    "fileMaxSize": 51200000, /* 上传大小限制,单位B,默认50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上传文件格式显示 */

    /* 列出指定目录下的图片 */
    "imageManagerActionName": "listimage", /* 执行图片管理的action名称 */
    "imageManagerListPath": "/ueditor/jsp/upload/image/", /* 指定要列出图片的目录 */
    "imageManagerListSize": 20, /* 每次列出文件数量 */
    "imageManagerUrlPrefix": "", /* 图片访问路径前缀 */
    "imageManagerInsertAlign": "none", /* 插入的图片浮动方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件类型 */

    /* 列出指定目录下的文件 */
    "fileManagerActionName": "listfile", /* 执行文件管理的action名称 */
    "fileManagerListPath": "/ueditor/jsp/upload/file/", /* 指定要列出文件的目录 */
    "fileManagerUrlPrefix": "", /* 文件访问路径前缀 */
    "fileManagerListSize": 20, /* 每次列出文件数量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件类型 */

}

5、新增Ueditor请求处理控制器

新增 ruoyi-admin\controller\common\UeditorController.java

package com.ruoyi.web.controller.common;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.file.FileUploadUtils;

/**
 * Ueditor 请求处理
 *
 * @author ruoyi
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping("/ajax/libs/ueditor")
public class UeditorController extends BaseController
{
    private final String METHOD_HEAD = "ueditor";
    private final String IMGE_PATH = "/ueditor/images/";
    private final String VIDEO_PATH = "/ueditor/videos/";
    private final String FILE_PATH = "/ueditor/files/";

    @Autowired
    private ServerConfig serverConfig;

    /**
     * ueditor
     */
    @ResponseBody
    @RequestMapping(value = "/ueditor/controller")
    public Object ueditor(HttpServletRequest request, @RequestParam(value = "action", required = true) String action,
            MultipartFile upfile) throws Exception
    {
        List<Object> param = new ArrayList<Object>()
        {
            {
                add(action);
                add(upfile);
            }
        };
        Method method = this.getClass().getMethod(METHOD_HEAD + action, List.class, String.class);
        return method.invoke(this.getClass().newInstance(), param, serverConfig.getUrl());
    }

    /**
     * 读取配置文件
     */
    public JSONObject ueditorconfig(List<Object> param, String fileSuffixUrl) throws Exception
    {
        ClassPathResource classPathResource = new ClassPathResource("ueditor-config.json");
        String jsonString = new BufferedReader(new InputStreamReader(classPathResource.getInputStream())).lines().parallel().collect(Collectors.joining(System.lineSeparator()));
        JSONObject json = JSON.parseObject(jsonString, JSONObject.class);
        return json;
    }

    /**
     * 上传图片
     */
    public JSONObject ueditoruploadimage(List<Object> param, String fileSuffixUrl) throws Exception
    {
        JSONObject json = new JSONObject();
        json.put("state", "SUCCESS");
        json.put("url", ueditorcore(param, IMGE_PATH, false, fileSuffixUrl));
        return json;
    }

    /**
     * 上传视频
     */
    public JSONObject ueditoruploadvideo(List<Object> param, String fileSuffixUrl) throws Exception
    {
        JSONObject json = new JSONObject();
        json.put("state", "SUCCESS");
        json.put("url", ueditorcore(param, VIDEO_PATH, false, fileSuffixUrl));
        return json;
    }

    /**
     * 上传附件
     */
    public JSONObject ueditoruploadfile(List<Object> param, String fileSuffixUrl) throws Exception
    {
        JSONObject json = new JSONObject();
        json.put("state", "SUCCESS");
        json.put("url", ueditorcore(param, FILE_PATH, true, fileSuffixUrl));
        return json;
    }

    public String ueditorcore(List<Object> param, String path, boolean isFileName, String fileSuffixUrl)
            throws Exception
    {
        MultipartFile upfile = (MultipartFile) param.get(1);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = FileUploadUtils.upload(filePath, upfile);
        String url = fileSuffixUrl + fileName;
        return url;
    }
}

6、登录系统,进入通知公告菜单测试富文本操作。

   
分类:Java/OOP 作者:无限繁荣, 吴蓉 发表于:2024-03-04 16:28:59 阅读量:97
<<   >>


powered by kaifamiao