springboot集成ueditor富文本编辑器(需要修改ueditor源码)

背景

最近工作需要重新搭建公司网站,其中需要使用富文本编辑器,货比三家,最后选择了百度团队的UEditor。项目框架为springboot,所以涉及到springboot集成ueditor,动手之前就听说会有不少坑...上手了发现,emm,果不其然...(主要是上传图片部分)
具体的集成步骤如下,希望这可以帮到看文章的你。
(本人使用的是ueditor-JSP版)

本篇为在修改UEditor源码的情况下集成的UEditor,如果需要不修改UEditor源码的请戳这里
springboot集成ueditor富文本编辑器(不修改ueditor源码)

相关源码下载

集成步骤:

  • 1 新建springboot项目,添加web和thymeleaf依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--修改thymeleaf版本-->
        <thymeleaf.version>3.0.3.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.1.0</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  • 2 下载对应的UEditor源码(完整版或者JSP版本均可):
    下载完成后解压至项目的resources/static/目录下,并将源码中的index.html复制到templates中,并修改其中引入js的src
    <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"> </script>
    <!--建议手动加在语言,避免在ie下有时因为加载语言失败导致编辑器加载失败-->
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" src="/ueditor/lang/zh-cn/zh-cn.js"></script>

注:同时另需要将UEditor中jsp目录下的config.json复制到项目的resources根目录下[重要]
注:将完整版源码中的/jsp/src/下的文件夹复制到项目的src文件夹下 [重要]

将源码拷贝至项目中.png

  • 3 创建UEditorContorller类,写跳转主页面方法
package com.example.demo.Controller;
import ...
@Controller
public class UEditorController {
    @RequestMapping("/")
    private String showPage(){
        return "index";
    }
}
  • 4 运行项目,浏览器地址栏输入http://localhost:8080/,进行第一次测试,如果出现以下内容,就可以继续下去啦~

    第一次测试成功结果.png

    此时点击图片上传按钮会显示后台配置项返回格式出错,上传功能将不能正常使用! 接下来就是配置关于图片上传的步骤啦!
    后端配置项未加载.png

  • 5 引入UEditor相关的依赖

<!--UEditor依赖的jar包 -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
</dependency>
  • 6 在UEditorController中写入config映射
package com.example.demo.Controller;
import ...
@Controller
public class UEditorController {
    @RequestMapping("/")
    private String showPage(){
        return "index";
    }

@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();  
        }  
    }  
}
  • 7 修改ConfigManage类的getConfigPath()方法
private String getConfigPath () {
        //return this.parentPath + File.separator + ConfigManager.configFileName;
        /*=========手动修改部分=========*/
        try{
            //获取classpath下的config.json路径
            return this.getClass().getClassLoader().getResource("config.json").toURI().getPath();
        }catch (URISyntaxException e){
            return null;
        }
    }
  • 8 配置ueditor.config.js
    打开ueditor.config.js
将:
, serverUrl: URL + "jsp/controller.jsp"
替换为:
, serverUrl: "/config"
  • 9 修改BinaryUploader 类,解决其无法获得带字节流的request的问题
    打开com.baidu.ueditor.upload.BinaryUploader.java,修改为:
public class BinaryUploader {  
  
    public static final State save(HttpServletRequest request,  
            Map<String, Object> conf) {  
        // FileItemStream fileStream = null;  
        // boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;  
  
        if (!ServletFileUpload.isMultipartContent(request)) {  
            return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);  
        }  
  
        // ServletFileUpload upload = new ServletFileUpload(  
            //  new DiskFileItemFactory());  
        //  
        // if ( isAjaxUpload ) {  
        //     upload.setHeaderEncoding( "UTF-8" );  
        // }  
  
        try {  
            // FileItemIterator iterator = upload.getItemIterator(request);  
            //  
            // while (iterator.hasNext()) {  
            //  fileStream = iterator.next();  
            //  
            //  if (!fileStream.isFormField())  
            //      break;  
            //  fileStream = null;  
            // }  
            //  
            // if (fileStream == null) {  
            //  return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);  
            // }  
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
            MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());  
            if(multipartFile==null){  
                return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);  
            }  
  
            String savePath = (String) conf.get("savePath");  
            //String originFileName = fileStream.getName();  
            String originFileName = multipartFile.getOriginalFilename();  
            String suffix = FileType.getSuffixByFilename(originFileName);  
  
            originFileName = originFileName.substring(0,  
                    originFileName.length() - suffix.length());  
            savePath = savePath + suffix;  
  
            long maxSize = ((Long) conf.get("maxSize")).longValue();  
  
            if (!validType(suffix, (String[]) conf.get("allowFiles"))) {  
                return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);  
            }  
  
            savePath = PathFormat.parse(savePath, originFileName);  
  
            String physicalPath = (String) conf.get("rootPath") + savePath;  
  
            //InputStream is = fileStream.openStream();  
            InputStream is = multipartFile.getInputStream();  
            State storageState = StorageManager.saveFileByInputStream(is,  
                    physicalPath, maxSize);  
            is.close();  
  
            if (storageState.isSuccess()) {  
                storageState.putInfo("url", PathFormat.format(savePath));  
                storageState.putInfo("type", suffix);  
                storageState.putInfo("original", originFileName + suffix);  
            }  
  
            return storageState;  
        // } catch (FileUploadException e) {  
        //  return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);  
        } catch (IOException e) {  
        }  
        return new BaseState(false, AppInfo.IO_ERROR);  
    }  
  
    private static boolean validType(String type, String[] allowTypes) {  
        List<String> list = Arrays.asList(allowTypes);  
  
        return list.contains(type);  
    }  
}  
  • 10 修改图片上传路径
    打开config.json,在其中增加:
“basePath”:“E:/image/”,

打开ConfigManager.java

在
conf.put( "savePath", savePath );
conf.put( "rootPath", this.rootPath );
上面加一句:
conf.put( "basePath", this.jsonConfig.getString("basePath") );

打开BinaryUploader.java

将
String physicalPath = (String) conf.get("rootPath") + savePath;
修改为
String basePath=(String) conf.get("basePath");
String physicalPath = basePath + savePath;

打开application.properties新增

web.upload-path=E:/  
spring.mvc.static-path-pattern=/**  
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}  

运行项目,发现此时的ueditor的图片上传就可以正常使用了!


配置成功.png

至此,springboot集成ueditor已经结束,希望可以帮到大家。

总结:

此次springboot集成ueditor中,主要遇到的难题就是关于后台config.json的路径配置出错,后来经查找资料发小可以自己手动写一个类来存储该json,不使用其自带的config.json。

参考博文:很详细的SpringBoot整合UEditor教程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269