SpringBoot集成UEditor富文本

5 篇文章 0 订阅
1 篇文章 0 订阅
前提

一个完整的SpringBoot项目;
下载:UEditor-开发版

第一步:准备工作

解压下载好的UEditor-开发版,把整个文件夹拷贝到项目的static目录下:最好文件夹名称改成ueditor,这样方便查阅代码
最重要的两个配置文件
pom.xml文件加上需要依赖的jar包:

<!-- 添加Ueditor依赖 -->
		<dependency>
			<groupId>com.baidu.ueditor</groupId>
			<artifactId>ueditor</artifactId>
			<version>1.1.2</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.json/json -->
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.9</version>
		</dependency>
<!-- 添加Ueditor依赖 -->


第二步:实例化编辑器

在需要的HTML页面上加上富文本编辑器:记得加载ueditor文件夹下的js包

    <script src="ueditor/ueditor.config.js"></script>
    <script src="ueditor/ueditor.all.min.js"></script>
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型,比如你在配置项目里配置的是英文,这里加载的中文,那最后就是中文-->
    <script src="ueditor/lang/zh-cn/zh-cn.js"></script>

    <div id="editor" type="text/plain" ></div>

实例化编辑器:从默认版本自定义版本选一个就好了

<scrpt  type="text/javascript">
//建议使用工厂方法getEditor创建和引用编辑器实例,如果在某个闭包下引用该编辑器,直接调用UE.getEditor('editor')就能拿到相关的实例
//默认版本
var ue = UE.getEditor('editor');

//自定义版本
var ue = UE.getEditor('editor',{
	        toolbars: [
	            [
	                'fontfamily', //字体
	                'fontsize', //字号
	                'undo', //撤销
	                'redo', //重做
	                '|',
	                'emotion', //表情
	                'forecolor', //字体颜色
	                'backcolor', //背景色
	                'bold', //加粗
	                'underline', //下划线
	                'strikethrough', //删除线
	                '|',
	                'justifyleft', //居左对齐
	                'justifyright', //居右对齐
	                'justifycenter', //居中对齐
	                '|',
	                'link', //超链接
	                'unlink', //取消链接
	                'simpleupload', //单图上传
	                'insertimage', //多图上传
	                //'music', //音乐
	                //'insertvideo', //视频
	                'removeformat', //清除格式
	                'formatmatch'//格式刷
	
	            ]
	        ],enableAutoSave:false,
	        autoHeightEnabled: true,
	        autoFloatEnabled: true,
	        initialFrameWidth:"100%", //初始化宽度
	        initialFrameHeight:300,
	        scaleEnabled:true//滚动条
	    });
</scrpt>

这时候打开HTML页面就能看到富文本了。

注意:这里说下给富文本赋值

 	//获取富文本的值,赋值给data
    ue.ready(function(){
        ue.setContent("赋值");
    });
第三步:配置上传功能

修改ueditor.config.js文件:

		// 服务器统一请求接口路径
         serverUrl:  "/config"

把原先的路径换成这个
新建一个UeditorController.java类:

我一开始用这个方法可以行的;但是当SpringBoot打成jar包部署到服务器时就报错,页面提示 "获取配置文件失败",
具体为什么我也没搞清楚
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassNamw UeditorController
 * @Description TODO
 * @Author //LMD
 * @Date 2019/7/15 9:09
 * @Version 1.0
 **/
@Controller
public class UeditorController {


    @RequestMapping(value = "/config1")
    public void config(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/json");
        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"ueditor/jsp";
        try {
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ActionEnter(request,rootPath).exec());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

后来我就这就重定向到配置文件下了:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassNamw UeditorController
 * @Description TODO
 * @Author //LMD
 * @Date 2019/7/15 9:09
 * @Version 1.0
 **/
@Controller
public class UeditorController {
    @RequestMapping("/config")
    public String config(String action,HttpServletRequest request,HttpServletResponse response) {
        return "redirect:/ueditor/jsp/config.json";
    }
}

新建上传类UpdloadFileController.java:
富文本上传图片返回数据结构就得这样:

{"title":"图片名","original":"图片名","url":"图片路径","state":"SUCCESS"}
import com.stcn.iformation.config.ConnUtil;
import com.stcn.iformation.config.ResultInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
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 org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static java.util.UUID.randomUUID;

/**
 * @ClassNamw UpdloadFile
 * @Description TODO
 * @Author //LMD
 * @Date 2019/6/19 15:32
 * @Version 1.0
 **/
@Controller
@RequestMapping("/common")
public class UpdloadFileController {

    private static Logger LOG = LoggerFactory.getLogger(UpdloadFileController.class);

    @Value("${FileUploadFolder}")
    private String uploadFolder;
    /**
     * 单文件上传
     * @param request
     * @return
     */
    @PostMapping("/uploadImage")
    @ResponseBody
    public Map<String,String> uploadImage(HttpServletRequest request) {

        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("upfile");

        MultipartFile file = files.get(0);
        if (file.isEmpty()) {
            return null;
        }
        //源文件名称
        String fileName = file.getOriginalFilename(); //文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-","");
        //文件后缀名
        String fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length());
        //文件存放目录:配置跟目录 + 生成的唯一标识 + 文件后缀名
        String filePath = uploadFolder + newFileName + fileType;
        System.out.println("filePath:"+filePath);
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
        } catch (IOException e) {
            LOG.error(e.toString(), e);
            return null;
        }
        Map<String,String> map = new HashMap();
        map.put("title",newFileName+fileType);
        map.put("original",newFileName+fileType);
        map.put("url","/image-path/"+newFileName+fileType);
        map.put("state","SUCCESS");
        return map;
    }
}

在HTML页面上加上监控图片上传操作:
'/common/uploadImage':这个路径就是上面的上传接口路径

    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
        // 如果触发了下面三个动作中,则进行文件上传操作
        if (  action == 'uploadscrawl' || action == 'uploadimage') {
            return '/common/uploadImage';
        } else {
            return this._bkGetActionUrl.call(this, action);
        }
    };

这样都配置好的话,就可以正常使用UEditor富文本了。

最后

在开发的工程中遇到什么问题可以,留言讨论。
有什么地方写的不好的,望包含。

感谢Forever_and_ever的原文:spring boot整合UEditor,不改源码,真实有效.

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值