springboot+thymeleaf集成百度Ueditor并自定义上传文件路径

最近项目需要,需要在发布通知时使用富文本编辑器,由于以前使用过jsp版的百度ueditor,所以就继续选择了ueditor富文本编辑器,由于使用thymeleaf模板不再支持jsp页面,因此走了不少坑,所以写下此博文记录,如果更好的方案,请指点:

1.首先下载百度ueditor jsp版本代码:https://ueditor.baidu.com/website/download.html

2.下载后解压并将ueditor复制到 src/main/resources/static根目录下,如图

504b57df6ae8dae8b9671f21a9eae511

3.将ueditor下的index.html复制到 src/main/resources/templates根目录下作为测试案例,如图:

5099195fe6905fe0ec55d62517f85b63

并更改相应的js文件css文件的引用路径如下:

 <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>
  • 6 创建Ueditor对象
package com.so.demosboot.common.ueditor;

public class Ueditor {
	private  String state;
	private  String url;
	private  String title;
	private  String original;

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }
}

创建PublicMsg 对象

package com.so.demosboot.common.ueditor;

public class PublicMsg {
	public final static String UEDITOR_CONFIG = "{n" +
            "    "imageActionName": "uploadimage",n" +
            "    "imageFieldName": "upfile",n" +
            "    "imageMaxSize": 2048000,n" +
            "    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],n" +
            "    "imageCompressEnable": true,n" +
            "    "imageCompressBorder": 1600,n" +
            "    "imageInsertAlign": "none",n" +
            "    "imageUrlPrefix": "",n" +
            "    "imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "n" +
            "    "scrawlActionName": "uploadscrawl",n" +
            "    "scrawlFieldName": "upfile",n" +
            "    "scrawlPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "    "scrawlMaxSize": 2048000,n" +
            "    "scrawlUrlPrefix": "",n" +
            "    "scrawlInsertAlign": "none",n" +
            "n" +
            "    "snapscreenActionName": "uploadimage",n" +
            "    "snapscreenPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "    "snapscreenUrlPrefix": "",n" +
            "    "snapscreenInsertAlign": "none",n" +
            "n" +
            "    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],n" +
            "    "catcherActionName": "catchimage",n" +
            "    "catcherFieldName": "source",n" +
            "    "catcherPathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "    "catcherUrlPrefix": "",n" +
            "    "catcherMaxSize": 2048000,n" +
            "    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],n" +
            "n" +
            "    "videoActionName": "uploadvideo",n" +
            "    "videoFieldName": "upfile",n" +
            "    "videoPathFormat": "/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "    "videoUrlPrefix": "",n" +
            "    "videoMaxSize": 102400000,n" +
            "    "videoAllowFiles": [n" +
            "        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",n" +
            "        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"],n" +
            "n" +
            "    "fileActionName": "uploadfile",n" +
            "    "fileFieldName": "upfile",n" +
            "    "filePathFormat": "/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}",n" +
            "    "fileUrlPrefix": "",n" +
            "    "fileMaxSize": 51200000,n" +
            "    "fileAllowFiles": [n" +
            "        ".png", ".jpg", ".jpeg", ".gif", ".bmp",n" +
            "        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",n" +
            "        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",n" +
            "        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",n" +
            "        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"n" +
            "    ],n" +
            "n" +
            "    "imageManagerActionName": "listimage",n" +
            "    "imageManagerListPath": "/ueditor/jsp/upload/image/",n" +
            "    "imageManagerListSize": 20,n" +
            "    "imageManagerUrlPrefix": "",n" +
            "    "imageManagerInsertAlign": "none",n" +
            "    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"],n" +
            "n" +
            "    "fileManagerActionName": "listfile",n" +
            "    "fileManagerListPath": "/ueditor/jsp/upload/file/",n" +
            "    "fileManagerUrlPrefix": "",n" +
            "    "fileManagerListSize": 20,n" +
            "    "fileManagerAllowFiles": [n" +
            "        ".png", ".jpg", ".jpeg", ".gif", ".bmp",n" +
            "        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",n" +
            "        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",n" +
            "        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",n" +
            "        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"n" +
            "    ] n" +
            "n" +
            "}";
    /**
     * Ueditor的返回状态类型
     */
    public enum UeditorMsg{
        SUCCESS("SUCCESS"),ERROR("上传失败");
        private String v;
        UeditorMsg(String v){
            this.v =v;
        }
        public String get(){
            return this.v;
        }
    }
}

新建ueditor文件上传处理控制类

package com.so.demosboot.common.ueditor;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.so.demosboot.modules.share.entity.Items;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by DEMOCXY on 2018-01-09.
 */
@RestController
@RequestMapping(value = "/ueUploadController")
public class UeUploadController {

	private String baseUrl ="H:/project";// 拿到配置文件配置的路径

	/**
	 * 获取json字符串 代替jsp文件配置
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/ueditor")
    public String ueditor(HttpServletRequest request) {

        return PublicMsg.UEDITOR_CONFIG;
    }
	
	/**
	 * 跳转到测试案例页面
	 * @param items
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "index")
	public String ue(Items items, Model model) {
		return "index";
	}
	
	/**
	 * 自定义文件上传方法
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/upload")
	public Map<String, Object> upPic(@RequestParam(value = "upfile", required = false) MultipartFile pic,
			String type,HttpServletRequest request, HttpServletResponse response) throws IOException {
		String saveUrl = "/upload/2019sharegoods";//文件保存路径前缀 必须包含upload
		if (type!=null && type !="") {
			if (type.startsWith("image")) {
				saveUrl += "/image/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
			}else if (type.startsWith("video")) {
				saveUrl += "/video/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
			}else{
				saveUrl += "/file/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
			}
		} else {
			saveUrl += "/" + new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
		}
		JSONObject json = new JSONObject();
		try {
			String fileName = pic.getOriginalFilename();
			String oldName = fileName;
			String fileType = fileName.substring(fileName.indexOf(".") + 1);
			// 生成随机字符串名,防止出现中文乱码的情况
			fileName = getRandomString(15) + "." + fileType;
			File dest = new File(baseUrl + saveUrl + "/" + fileName);
			if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
				dest.getParentFile().mkdirs();
			}
			pic.transferTo(dest); // 保存文件
			//按照相应的json数据格式返回结果
			json.put("state", "SUCCESS");
			json.put("title", oldName);
			json.put("url", saveUrl + fileName);// 图片访问 相对路径
			json.put("original", pic.getName());
		} catch (Exception e) {
			json.put("state", "ERROR");
			e.printStackTrace();
		}
		//System.out.println(json.toString());
		response.getWriter().print(json.toString());
		return null;
	}
	
	
	/**
	 * @Title: getRandomString
	 * @Description: 随机生成字符串
	 * @param @param
	 *            length 字符串长度
	 * @return String
	 * @date createTime:2018年4月9日下午1:45:52
	 */
	public static String getRandomString(int length) {
		// 产生随机数
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		// 循环length次
		for (int i = 0; i < length; i++) {
			// 产生0-2个随机数,既与a-z,A-Z,0-9三种可能
			int number = random.nextInt(3);
			long result = 0;
			switch (number) {
			// 如果number产生的是数字0;
			case 0:
				// 产生A-Z的ASCII码
				result = Math.round(Math.random() * 25 + 65);
				// 将ASCII码转换成字符
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				// 产生a-z的ASCII码
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				// 产生0-9的数字
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}

	
}

修改ueditor.config.js serverUrl路径

8a2249acf051f4b428d8fce4388105cb

html界面添加自定义文件上传方法配置:

 UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;  
	    UE.Editor.prototype.getActionUrl = function(action) {  
	        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'listimage') {  
	            return '/ueUploadController/upload?type=image';  
	        }if(action == 'uploadvideo'){
	        	return '/ueUploadController/upload?type=video';
	        }if(action == 'uploadfile'){
	        	return '/ueUploadController/upload?type=video';
	        } else {  
	            return this._bkGetActionUrl.call(this, action); 
	        }  
	    } 

最后配置虚拟路径(因为自定义文件上传 我把文件上传到了H:/project/upload/2019sharegoods/**.png下面)

保存在数据库的路径是/upload/2019sharegoods/**.png

所以虚拟 路径配置代码如下

@Configuration
public class WebConfig implements WebMvcConfigurer {


    // 这个方法是用来配置静态资源的,比如html,js,css,等等
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    	registry.addResourceHandler("/upload/**").addResourceLocations("file:/H:/project/upload/");
    }
  }

至此 所有步骤已经完全实现,是不是感觉少了点什么???

没错,至始至终我们都没有使用到下载源码里面的java代码,也没有引入jsp文件下的lib包,因为我们使用的是自定义文件上传路径,上传方法是自己写的,所以无需使用,不用质疑。

UEditor文档 http://fex.baidu.com/ueditor/

springboot+thymeleaf集成百度Ueditor并自定义上传文件路径
滚动到顶部