1. 程式人生 > >SpringBoot整合UEditor教程

SpringBoot整合UEditor教程

UEditor只提供JSP版本的後端入口程式碼。但提供了專案原始碼,因此可以根據業務需求修改原始碼。

1.新建SpringBoot專案

pom檔案如下:

<?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>ueditor-test</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>ueditor-test</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.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>
			</properties>
	<dependencies>

		<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>

		<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>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2.從官網下載原始碼並解壓至專案resources/static下,注意config.json我拷到了ueditor路徑下,ueditor.jar有些類需要修改原始碼,我全拿出來了,後面就不需要新增這個jar包了,如圖:

4.寫入UEditorController類,對映路徑為ueditor/config。

package com.example;

import com.baidu.ueditor.ActionEnter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by ldb on 2017/4/9.
 */
@Controller
@RequestMapping("/ueditor")
public class UEditorController {
    
    @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();
        }

    }
}

5.一步一步debug,發現無法載入config.json檔案。此時修改ConfigManage類的getConfigPath()方法。如下:

package com.baidu.ueditor;
 
import com.baidu.ueditor.define.ActionMap;
import org.json.JSONArray;
import org.json.JSONObject;
 
import java.io.*;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 配置管理器
 * @author 
[email protected]
* */ public final class ConfigManager { private final String rootPath; private final String originalPath; private final String contextPath; private static final String configFileName = "config.json"; private String parentPath = null; private JSONObject jsonConfig = null; // 塗鴉上傳filename定義 private final static String SCRAWL_FILE_NAME = "scrawl"; // 遠端圖片抓取filename定義 private final static String REMOTE_FILE_NAME = "remote"; /* * 通過一個給定的路徑構建一個配置管理器, 該管理器要求地址路徑所在目錄下必須存在config.properties檔案 */ private ConfigManager ( String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException { rootPath = rootPath.replace( "\\", "/" ); this.rootPath = rootPath; this.contextPath = contextPath; if ( contextPath.length() > 0 ) { this.originalPath = this.rootPath + uri.substring( contextPath.length() ); } else { this.originalPath = this.rootPath + uri; } this.initEnv(); } /** * 配置管理器構造工廠 * @param rootPath 伺服器根路徑 * @param contextPath 伺服器所在專案路徑 * @param uri 當前訪問的uri * @return 配置管理器例項或者null */ public static ConfigManager getInstance ( String rootPath, String contextPath, String uri ) { try { return new ConfigManager(rootPath, contextPath, uri); } catch ( Exception e ) { return null; } } // 驗證配置檔案載入是否正確 public boolean valid () { return this.jsonConfig != null; } public JSONObject getAllConfig () { return this.jsonConfig; } public Map<String, Object> getConfig ( int type ) { 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; } conf.put( "savePath", savePath ); conf.put( "rootPath", this.rootPath ); return conf; } private void initEnv () throws FileNotFoundException, IOException { File file = new File( this.originalPath ); if ( !file.isAbsolute() ) { file = new File( file.getAbsolutePath() ); } this.parentPath = file.getParent(); String configContent = this.readFile( this.getConfigPath() ); try{ JSONObject jsonConfig = new JSONObject( configContent ); this.jsonConfig = jsonConfig; } catch ( Exception e ) { this.jsonConfig = null; } } 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; } } private String[] getArray ( String key ) { JSONArray jsonArray = this.jsonConfig.getJSONArray( key ); String[] result = new String[ jsonArray.length() ]; for ( int i = 0, len = jsonArray.length(); i < len; i++ ) { result[i] = jsonArray.getString( i ); } return result; } private String readFile ( String path ) throws IOException { StringBuilder builder = new StringBuilder(); try { InputStreamReader reader = new InputStreamReader( new FileInputStream( path ), "UTF-8" ); BufferedReader bfReader = new BufferedReader( reader ); String tmpContent = null; while ( ( tmpContent = bfReader.readLine() ) != null ) { builder.append( tmpContent ); } bfReader.close(); } catch ( UnsupportedEncodingException e ) { // 忽略 } return this.filter( builder.toString() ); } // 過濾輸入字串, 剔除多行註釋以及替換掉反斜槓 private String filter ( String input ) { return input.replaceAll( "/\\*[\\s\\S]*?\\*/", "" ); } }

this.getClass().getClassLoader().getResource("config.json").toURI().getPath();  此處需要先轉為URI再getPath(),否則如果你的專案路徑帶空格或者帶中文則無法讀取到檔案

6.執行專案路徑http://localhost:8080/config?action=config,如下圖顯示則表示可讀取到config.json檔案

7.上傳個圖片成功了

8..可是圖片究竟上傳到哪裡了呢?繼續一步步debug發現,上傳到如圖路徑

如圖路徑為tomcat快取路徑,只要重啟下tomcat該檔案就會被刪除。我們需要將其儲存到磁碟中。此時修改config.json檔案。

紅色箭頭為修改處。我需要將檔案儲存到E:/image/**下,此處我多添加了basePath,是想把視訊、音樂等靜態資源都儲存到E盤。由於添加了basePath,需要修改配置。通過debug來到ConfigManage

新增紅色箭頭程式碼,將basePath塞進配置檔案裡。之後繼續來到上傳檔案類BinaryUploader,修改如下程式碼:

執行專案,點選新增圖片。開啟E盤的image目錄,如圖,成功上傳到E盤對應路徑

執行專案,點選新增圖片。開啟E盤的image目錄,如圖,成功上傳到E盤對應路徑

9.開啟瀏覽器,發現頁面無法載入圖片。如下圖:

無法獲取到圖片。這是當然的,因為我們把圖片存在E盤了,而spring並沒有對E盤目錄進行對映。此時我們加入路徑對映。開啟application.properties檔案,新增如下程式碼

spring.resources.static-locations=classpath:static/,file:static/,file:E:/

此時重新執行專案,點選上傳圖片,圖片已經能夠正常顯示了。

10.至此,SpringBoot整合UEditor應該完了吧。別急,SpringBoot主張打包成Jar包執行,我們用Maven來打包執行試試

java -jar  開啟專案地址,點選上傳圖片,發現竟然上傳不了了??!!

這是怎麼回事呢?為什麼打成Jar包後就無法上傳圖片了呢。經過不斷的debug和google。。發現了在Jar包裡無法以ClassLoader.getResource().getPath()獲得的路徑讀取檔案,得用Class類的getResourceAsStream()來讀取。具體博文如下:

http://hxraid.iteye.com/blog/483115?page=3#comments

11.那麼我們就來修改原始碼,改成getResourceAsStream讀取config.json檔案吧。開啟ConfigManager類,修改initEnv方法

private void initEnv () throws FileNotFoundException, IOException {
		
		File file = new File( this.originalPath );
		
		if ( !file.isAbsolute() ) {
			file = new File( file.getAbsolutePath() );
		}
		
		this.parentPath = file.getParent();
		
		//String configContent = this.readFile( this.getConfigPath() );
		String configContent = this.filter(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("config.json")));
 
		try{
			JSONObject jsonConfig = new JSONObject( configContent );
			this.jsonConfig = jsonConfig;
		} catch ( Exception e ) {
			this.jsonConfig = null;
		}
		
	}

12. ok了,再次打包,執行專案

成功了!!!

本次教程到此結束。謝謝大家