您当前的位置: 首页 >  慌途L spring

SpringBoot 整合 UEditor 详细教程(一)| 整合教程

慌途L 发布时间:2020-09-02 18:52:38 ,浏览量:3

SpringBoot 整合 UEditor 详细教程(一)| 整合教程 官方文档:http://fex.baidu.com/ueditor/. 项目地址:https://github.com/fex-team/ueditor. 官方源码zip包(UTF-8格式):ueditor-1.4.3.3.zip(github下载过慢)
  • 链接:https://pan.baidu.com/s/1btFLz8PVXLot3CjL2qEiQQ
  • 提取码:mja2
一、下载源码包 1.由于官网下载过慢,我在上面贴了百度云的下载链接(JSP、UTF-8版)

下载后方式项目的放入静态文件夹static下: 在这里插入图片描述

2.引入 pom 依赖


    com.gitee.qdbp.thirdparty
    ueditor
    1.4.3.3


    commons-fileupload
    commons-fileupload
    1.3.2


    commons-codec
    commons-codec
    1.9

3.改写以前jsp获取 config.json(上传相关配置) 文件的方法 注意:
  • 图片不上传到云服务器的话需要做映射,可参考下一篇的踩坑文章

  • 这里我写的上传方法在本地可以使用,然后由于部署到线上时出现config.json不能读取,就将config.json文件单独放出来了,具体可看代码;

  • 还有一个问题就是上传图片,本地映射的方式在Linux服务器无法正常显示,搞了差不多一天,后面还是改成通过OSS上传到阿里云。(这里OSS上传代码就不贴了)

  • 如果大家服务器改好了可告诉博主,博主进行实践和更新。

这里改写了原来百度编辑器的两个类:ActionEnterConfigManager 大致就是将里面的内容重写一遍(ActionEnterRewrite、ConfigManagerRewrite ),用于部署到linux环境时打印日志定位问题,大家可重写也可重写,主要用于定位每次获取config.json的获取路径

重写文件下载地址:

  • 链接:https://pan.baidu.com/s/1JTyc_sHoQBlUCmhrXkN9rA
  • 提取码:osfi
/**
 * 描述: 百度编辑器引入
 * 创建人: 慌途L
 */
@Slf4j
@RestController
public class UEditorController {
    /**
     * 获取config,json配置文件
     */
    @RequestMapping("/ueditor/config")
    public void getConfigInfo(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");

        String rootPath = "";
        // 判断当前系统是否是Windows系统
        if(isWindowsSystem()){
            rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "static/ueditor/jsp";
        } else {
            // 将config.json文件放在jar包同级目录下
            rootPath = "/usr/local/yunapp-backend/service";
        }
        log.info("rootPath:{}", rootPath);
        try {
            response.setCharacterEncoding("UTF-8");
            String exec = new ActionEnterRewrite(request, rootPath, "/config.json").exec();
            log.info("exec:{}", UnicodeUtil.toString(exec));
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * UEditor 上传图片(单个或多个)---Windows使用(主要将config.json中的imageUrlPrefix改为本地地址)
     * @return  返回提示信息
     */
    @RequestMapping(value = "/ueditorUpload", method = RequestMethod.POST)
    public Object upLoadImgToWindows(MultipartFile upfile){
        Map map = new HashMap();
        map.put("state", "上传失败");

        if (Objects.isNull(upfile)) {
            return map;
        }

        String oldName = upfile.getOriginalFilename();
        String timeFileName = DateHelper.getDateStr(new Date());

        // 判断当前系统是否是Windows系统
        boolean system = isWindowsSystem();
        String fileName = system ? FileUtils.upLoadFile(upfile,"F:/upload/admin/article/" + timeFileName)
                : FileUtils.upLoadFile(upfile,imgUrl + "/" + timeFileName);
        if (StringUtils.isNotBlank(fileName)) {
            map.put("state", "SUCCESS");
            // 图片url 浏览器不能直接访问项目外目录的图片等文件,需要做虚拟路径映射
            // 这个路径的是在配置类里指定的映射到本地的绝对路径
            if(system){
                map.put("url", "/upload/admin/article/" + timeFileName + "/" + fileName);
            } else {
                map.put("url", "/" + mappingUrl + "/" + timeFileName + "/" + fileName);
            }
            //图片名称,这个会显示在输入框里
            map.put("title", fileName);
            //图片原名称
            map.put("original", oldName);
            //文件类型 .+后缀名
            map.put("type", fileName.substring(fileName.lastIndexOf(".")));
            //文件大小(字节数)
            map.put("size", upfile.getSize());
        }
        log.info("map:{}", map);
        return map;
    }

    /**
     * 判断当前系统是否是Windows系统
     * @return true:Windows系统,false:Linux系统
     */
    private boolean isWindowsSystem(){
        String property = System.getProperty("os.name").toLowerCase();
        return property.contains("windows");
    }

}

FileUtils.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * 功能 : 上传文件工具类
 * 创建人 : 慌途L
 */
@Slf4j
public class FileUtils {

    public static String upLoadFile(MultipartFile file, String path) {

        if(file.isEmpty()){
            log.info("文件为空!");
            return null;
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        log.info(fileName + "-->" + size);

        // 取得文件的后缀名。
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();

        String newFileName =
                System.currentTimeMillis() / 1000 + new Random().nextInt(100000)+"." + ext;

        //String path = "F:/test" ;
        File dest = new File(path + "/" + newFileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return newFileName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
}

4.修改 ueditor.config.js 文件中的入口路径

这里是百度编辑器初始化时读取config.json的方法路径

var server_url = window.location.protocol+"//"+window.location.hostname+":"+window.location.port;

在这里插入图片描述

5.测试文件 Demo.html:

(我这里用的是thymeleaf模板,有一些坑,就是在 script 标签中使用 UE.getEditor 时,需要使用下面的标签)





    
    Title
    
    
    
    
    
    



    
        
    




    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    console.log(UE.Editor.prototype.getActionUrl)
    console.log(UE.Editor.prototype._bkGetActionUrl)
    UE.Editor.prototype.getActionUrl = function(action) {
        if (action === 'uploadimage') {
            return '/ueditorUpload';// 此路径跟ueditor.config.js中的服务器统一请求接口路径一样,在同一个controller中
            // return 'http://localhost:8090/upLoadImg';//自定义别的请求接口的需要加上IP和端口
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    }

    var uee = UE.getEditor('ueditorContent', {
        toolbars: [[
            'fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'directionalityltr', 'directionalityrtl', 'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
            'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'insertimage', 'map', 'pagebreak', 'template', 'background', '|',
            'horizontal', 'date', 'time', 'spechars', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'preview', 'searchreplace', 'drafts'
        ]]
    });



6.回显的时候需要使用以下代码:
UE.getEditor('ueditorContent').execCommand('insertHtml', content);
  • ueditorContent:百度编辑器的ID
  • content:回显的内容
7.测试上传图片(这里的单图和多图上传都是调用同一个接口,只是多图为多次调用)

在这里插入图片描述 在这里插入图片描述

下一篇为遇到的踩坑点:SpringBoot 整合 UEditor 详细教程(二)| 遇到的问题.

具体踩坑点:

  • 1.自定义 toolbars 时出现 Could not parse as expression 异常
  • 2.前端报错:请求后台配置项http错误,上传功能将不能正常使用
  • 3.报错:“\u914d\u7f6e\u6587\u4ef6\u521d\u59cb\u5316\u5931\u8d25”(配置文件初始化失败)
  • 4.配置上传图片,报错 : 无效的Action
  • 5.注释多图上传里面的其他按钮
  • 6.注释部分功能无法使用的代码
  • 7.保存成功后无法正常显示文字和图片,或显示为空白
  • 8.部署到服务器又出现了第3点的问题,加载不到config.json文件
参考网址:
  • https://www.jianshu.com/p/241b2a401e32.
  • https://www.jianshu.com/p/9548878c3e5b.
  • https://blog.csdn.net/weixin_42132143/article/details/103783987.
关注
打赏
1688896170
查看更多评论

慌途L

暂无认证

  • 3浏览

    0关注

    118博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0874s