欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

maven项目中-富文本编辑器-百度ueditor-的使用

程序员文章站 2022-05-24 20:36:04
...

maven项目中-富文本编辑器-百度ueditor-的使用

一、下载ueditor插件包
https://ueditor.baidu.com/website/download.html
maven项目中-富文本编辑器-百度ueditor-的使用

二、 将插件放入maven项目中
maven项目中-富文本编辑器-百度ueditor-的使用
三、引入依赖
maven项目中-富文本编辑器-百度ueditor-的使用

mven依赖

<dependency>
            <groupId>com</groupId>
            <artifactId>baidu</artifactId>
            <version>1.1.2</version>
        </dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20160810</version>
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>

如果ueditor-1.1.2.jar无法引入的话需手动引入

mvn install:install-file -Dfile=ueditor-1.1.2.jar -DgroupId=com.baidu -DartifactId=ueditor -Dversion=1.1.2 -Dpackaging=jar

四、前台页面以及配置
直接使用官方给的index.html页面就可以,这里我也粘一份

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath }/plugins/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath }/plugins/ueditor/ueditor.all.js"> </script>
    <script type="text/javascript" charset="utf-8" src="${pageContext.request.contextPath }/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
	<style type="text/css">
        div{
            width:100%;
        }
    </style>
	
</head>
<div>
<!--     <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script> -->
    <textarea id="editor" name="editor" style="width:1024px;height:500px;">newSourceContent</textarea>
</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>

ueditor.config.js中修改

var getRootPath = function (){
        //获取当前网址
        var curWwwPath=window.document.location.href;
        //获取主机地址之后的目录
        var pathName=window.document.location.pathname;
        
        var pos=curWwwPath.indexOf(pathName);
        //获取主机地址
        var localhostPaht=curWwwPath.substring(0,pos);
        //var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
        return(localhostPaht);
    }
	var applicationPath = getRootPath();
	var serverURL = applicationPath;
    var URL = window.UEDITOR_HOME_URL || getUEBasePath();

    /**
     * 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
     */
    window.UEDITOR_CONFIG = {

        //为编辑器实例添加一个路径,这个不能被注释
        UEDITOR_HOME_URL: URL

        // 作为访问后台的路径
        , serverUrl: serverURL +"/user/hello.do"   

config.json中修改
“imageUrlPrefix”: “http://127.0.0.1:81/”, /* 图片访问路径前缀 */ (端口使用自己项目的端口)

五、后台配置

UserController

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("/hello")
    @ResponseBody
    public Object test(HttpServletRequest request,
                       @RequestParam(value = "action") String action, 
                       @RequestParam(value = "upfile", required = false) MultipartFile file) throws Exception {
       switch (action) {
           case "config": // 加载返回ueditor配置文件conf/config.json
               return ResourceUtils.getConfig();
           case "uploadimage": // 上传图片
               return ResourceUtils.uploadImage(request, file);
           case "uploadvideo": // 上传视频
               return "视频处理方法";
           case "uploadfile": // 上传文件
               return "文件处理方法";
           default:
               return "无效action";
        }
    }
}

ResourceUtils

 public static File getFile(String resourceLocation) throws FileNotFoundException {
        Assert.notNull(resourceLocation, "Resource location must not be null");
        if (resourceLocation.startsWith("classpath:")) {
            String path = resourceLocation.substring("classpath:".length());
            String description = "class path resource [" + path + "]";
            ClassLoader cl = ClassUtils.getDefaultClassLoader();
            URL url = cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path);
            if (url == null) {
                throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not exist");
                
            }else{
                return getFile(url, description);
            }
        }else{
            try {
                return getFile(new URL(resourceLocation));
            }catch (MalformedURLException var5) {
                return new File(resourceLocation);
            }
        }
    }
    public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
        Assert.notNull(resourceUrl, "Resource URL must not be null");
        if (!"file".equals(resourceUrl.getProtocol())) {
            throw new FileNotFoundException(description + " cannot be resolved to absolute file path because it does not reside in the file system: " + resourceUrl);
        }else{
            try {
                return new File(toURI(resourceUrl).getSchemeSpecificPart());
            } catch (URISyntaxException var3) {
                return new File(resourceUrl.getFile());
            }
        }
    }
    public static URI toURI(URL url) throws URISyntaxException {
        return toURI(url.toString());
    }
    public static URI toURI(String location) throws URISyntaxException {
        return new URI(StringUtils.replace(location, " ", "%20"));
    }
    public static File getFile(URL resourceUrl) throws FileNotFoundException {
        return getFile(resourceUrl, "URL");
    }
    
    public static String getConfig() throws Exception {
        File file = ResourceUtils.getFile("classpath:conf/config.json");
        String json = FileUtils.readFileToString(file, "utf-8");
        return json;
    }
    
    public static Map<String, Object> uploadImage(HttpServletRequest request, MultipartFile file) {
        String state = "SUCCESS";
        String savedDir = request.getSession().getServletContext().getRealPath("/upload");
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String extend = uuid+getExtend(filename);
        File filepath = new File(savedDir,extend);
        if (!filepath.getParentFile().exists()) {
            filepath.getParentFile().mkdirs();
        }
        // 写到服务器路径下,可扩展,比如上传到云端或文件服务器
        try {
			file.transferTo(new File(savedDir + File.separator + extend));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//上传到根目录的upload下
        String uploadHttpUrl = "/upload"+ File.separator + extend;
        return resultMap(file, state, uploadHttpUrl);
    }
    
    private static Map<String, Object> resultMap(MultipartFile file, String state, String uploadHttpUrl) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put("state", state);  //"SUCCESS" 表示成功
        resMap.put("title", file.getOriginalFilename());
        resMap.put("original", file.getOriginalFilename());
        resMap.put("type", file.getContentType());
        resMap.put("size", file.getSize());
        resMap.put("url", uploadHttpUrl);
        return resMap;
    }
    
    
    public static String getExtend(String fileName) {
		// TODO Auto-generated method stub
		return fileName.substring(fileName.lastIndexOf("."));
	}

这样整个ueditor就可以使用了
maven项目中-富文本编辑器-百度ueditor-的使用
这是我第一次写博客 以后也会将一些遇到问题的地方发到博客上 分享给大家 也可以防止自己以后再遇到类似的问题