SpringBoot项目集成Ueditor富文本

一、官网下载ueditor源码(https://ueditor.baidu.com/website/download.html),javaweb项目使用jsp版,解压后的文件目录如下:

  

  二、将源码添加到项目中

     1、把ueditor项目的java源码复制到自己项目中,修改导入包名

        

2、把ue的js的源代码复制添加到自己项目的静态资源文件夹static下,将config.json复制到templates:

三、配置图片上传的路径

1、  applicatio.yml上加入图片上传路径结点

  

  java配置:

@Configuration
public class ImageConfig  implements WebMvcConfigurer {
    @Value("${web.upload}")
    private String  path;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("图片上传路径==========="+path);
        //路径前面要使用file协议,本地路径使用/分隔
        registry.addResourceHandler("/img/**").addResourceLocations("file:"+path);
    }
}

四、修改Ueditor源码:

  1、改写controller.jsp,使用javad的Contorller实现

@Controller
@RequestMapping("/admin")
public class AdminController  extends BaseController {
    /**
     *  配置ue服务器统一请求接口路径http://localhost:8086/admin/ue
     */
    @RequestMapping("/ue")
    public  void configUEditor(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 (JSONException | IOException e) {
            e.printStackTrace();
        }

    }
}

 修改ueditor.config.js中 serverUrl的路径为http://localhost:8086/admin/ue

2、在config.json中添加图片上传的服务器根路径

  

3、修改java源代码:

    (1)修改ConfigManage类的getConfigPath()和getConfig方法

	private String getConfigPath () {
		//return this.parentPath + File.separator + ConfigManager.configFileName;
		try {
			//获取classpath下的config.json路径
			return Objects.requireNonNull(this.getClass().getClassLoader().getResource(configFileName)).toURI().getPath();
		} catch (URISyntaxException e) {
			return null;
		}
	}

   修改getConfig 方法, 获取图片上传的路径basePath

     conf.put("basePath",jsonConfig.getString("basePath"));

  


	public Map<String, Object> getConfig ( int type ) throws  JSONException {
		Map<String, Object> conf = new HashMap<String, Object>();
		String savePath = null;
		switch ( type ) {
			case ActionMap.UPLOAD_FILE:
				conf.put( "isBase64", "false" );
				conf.put( "maxSize", this.jsonConfig.getLong( "fileMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "fileAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "fileFieldName" ) );
				savePath = this.jsonConfig.getString( "filePathFormat" );
				break;
			case ActionMap.UPLOAD_IMAGE:
				conf.put( "isBase64", "false" );
				conf.put( "maxSize", this.jsonConfig.getLong( "imageMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "imageAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "imageFieldName" ) );
				savePath = this.jsonConfig.getString( "imagePathFormat" );
				break;
			case ActionMap.UPLOAD_VIDEO:
				conf.put( "maxSize", this.jsonConfig.getLong( "videoMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "videoAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "videoFieldName" ) );
				savePath = this.jsonConfig.getString( "videoPathFormat" );
				break;
				
			case ActionMap.UPLOAD_SCRAWL:
				conf.put( "filename", ConfigManager.SCRAWL_FILE_NAME );
				conf.put( "maxSize", this.jsonConfig.getLong( "scrawlMaxSize" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "scrawlFieldName" ) );
				conf.put( "isBase64", "true" );
				savePath = this.jsonConfig.getString( "scrawlPathFormat" );
				break;
				
			case ActionMap.CATCH_IMAGE:
				conf.put( "filename", ConfigManager.REMOTE_FILE_NAME );
				conf.put( "filter", this.getArray( "catcherLocalDomain" ) );
				conf.put( "maxSize", this.jsonConfig.getLong( "catcherMaxSize" ) );
				conf.put( "allowFiles", this.getArray( "catcherAllowFiles" ) );
				conf.put( "fieldName", this.jsonConfig.getString( "catcherFieldName" ) + "[]" );
				savePath = this.jsonConfig.getString( "catcherPathFormat" );
				break;
				
			case ActionMap.LIST_IMAGE:
				conf.put( "allowFiles", this.getArray( "imageManagerAllowFiles" ) );
				conf.put( "dir", this.jsonConfig.getString( "imageManagerListPath" ) );
				conf.put( "count", this.jsonConfig.getInt( "imageManagerListSize" ) );
				break;
				
			case ActionMap.LIST_FILE:
				conf.put( "allowFiles", this.getArray( "fileManagerAllowFiles" ) );
				conf.put( "dir", this.jsonConfig.getString( "fileManagerListPath" ) );
				conf.put( "count", this.jsonConfig.getInt( "fileManagerListSize" ) );
				break;
				default:
					break;
				
		}

		conf.put("basePath",jsonConfig.getString("basePath"));
		conf.put("savePath", savePath );
		conf.put("rootPath", this.rootPath );
		
		return conf;
		
	}

(2)运行测试加载

 (3)修改BinaryUploader,采用SpringMVC框架的解析器multipartResolver

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);
		}
		try {
			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 = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);
			originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
			savePath = savePath + suffix;
			long maxSize = (Long) conf.get("maxSize");
			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;
			String  basePath= (String) conf.get("basePath");
			String  physicalPath=basePath+savePath;

			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 (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);

	}

(4)pom文件加入图片上传所需的jar包依赖

    

 <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>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>

五、管理后台使用

<!DOCTYPE html>
<#include "../base.ftl">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>添加商品</title>
    <script type="text/javascript">
        /**创建ue对象*/
        var ue = UE.getEditor('editor');
        ue.ready(function () {
            ue.setContent("《长相思·一重山》");
        });
    </script>

</head>

<body>

<script id="editor" type="text/plain" name="content" style="width:100%;height:800px;"></script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/fengchengwu2012/article/details/85328926
今日推荐