1、将ueditor放入静态资源

Springboot使用Ueditor

注意图中红色剪头为重要配置,

其中的controller.jsp是后台统一入口(获取config.json和上传文件),由于被放入了静态资源,无法正常访问和执行,所以我们自己写方法覆盖掉它,

config.json在前端ue首次加载时会请求获取,里面都是一些关于上传文件和回显的配置,由于我们决定覆盖掉controller.jsp中的方法,所以config.json中关于上传的配置可以忽略,不需要修改它

只需要修改ueditor.config.js

2、添加依赖

<dependency>
    <groupId>com.gitee.qdbp.thirdparty</groupId>
    <artifactId>ueditor</artifactId>
    <version>1.4.3.3</version>
</dependency>

解释:原依赖在 ueditor/jsp/lib中,现已有人放入maven仓库中,直接放入pom即可

3、修改配置

a.修改ueditor.config.js,

Springboot使用Ueditor

大约在33行,这里填写成我们自己的上传文件接口,

还有其他例如工具栏的一些配置,参考官网api

4、覆盖原上传方法

@Controller
public class CommonController {

//	 private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	/**
	 * 文件上传路径
	 */
	public static final String UPLOAD_PATH = "/profile/upload/";

	@Autowired
	private ServerConfig serverConfig;
    
	@RequestMapping("/ueditor/config")
	public String config(String action,HttpServletRequest request,HttpServletResponse response) {
        System.out.println(action);
        if("config".equals(action)) {
        	return "redirect:/admin/plugins/ueditor/jsp/config.json";
        }else {
        	return "forward:/common/upload";
        }
    }

	/**
	 * 通用上传请求,注意返回数据,一定要这样写,这是ue需要的格式,保证回显
     * 文件参数必须是upfile,这是config.json中定义的
	 */
	@PostMapping("/common/upload")
	@ResponseBody
	public Map<String, Object> uploadFile(MultipartFile upfile) throws Exception {
		Map<String, Object> map = new HashMap<>(3);
		try {
			// 上传文件路径
			String filePath = WebConst.DEFAULT_UPLOAD_BASEDIR;
			// 这是我们的上传通用方法,上传到我们本地文件系统
			String fileName = FileUploadUtils.upload(filePath, upfile);
            //文件上传成功后一定要给一个访问路径,用于回显
			String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;
			map.put("url", url);
            map.put("state", "SUCCESS");
            map.put("original", "");
		} catch (Exception e) {
			map.put("url", "");
            map.put("state", "SUCCESS");
            map.put("original", "");
		}
		
		return map;
	}
}

解释:rest接口:/ueditor/config,即上一步配置的后台链接,从代码可知,前端ue插件获取配置(前端ue初始化时会通过这个链接获取config.json)和上传文件都是走的这里(通过action参数判断是获取参数还是上传文件),注意!!当上传文件时,直接转发到了我们的后台接口/common/upload,所以这时候config.json中的各种**ActionName和**UrlPrefix等配置失去了作用!!!所以需要我们的上传接口告诉前端资源的访问路径,用来作回显,注意返回的数据格式,上传接口中获取文件的参数名称必须是upfile,这是config.json中定义的

自定义上传的好处是可以自己处理文件,比如放在其他系统目录或者各种dfs系统,ue默认是放在当前项目路径不保险

Springboot使用Ueditor

4、成功

Springboot使用Ueditor

视频和图片都能正常上传和回显~~

5、备注一下小的使用技巧,比如自动截取文章前几百个字作为简介:

var ue = UE.getEditor('text',{
    initialFrameWidth:"100%",   //初始化宽度
    initialFrameHeight:400,     //初始化高度
});

//同步更新简介,富文本变化,简介跟着变化,展示效果会好些
ue.addListener('contentChange',function(editor){
    //相关操作
    var text = ue.getContentTxt();
    if(text.length>200){
        text = text.substring(0,200);
    }
    $("#remark").val(text);
});

 

相关文章: