開發環境:一個簡單的web項目中,用百度富文本編輯器 ueditor 實現圖片和文件的上傳(可自定義上傳路徑)
官網地址:http://ueditor.baidu.com/website/
DEMO地址:https://download.csdn.net/download/ikuno/10528025
需要使用到的2個文件如下(官網上下載):
1,ueditor-1.4.3.3.zip
2,ueditor1_4_3_3-utf8-jsp.zip
所需jar包:
集成步驟:參考官網說明(http://fex.baidu.com/ueditor/#server-jsp),我這裏僅僅做了下調整,爲了省事直接修改的controller.jsp。
配置完成後,把解壓源碼包得到的ueditor-1.4.3.3裏面有一個jsp目錄,進入C:\Users\92307\Desktop\ueditor-1.4.3.3\jsp\src 下,把com文件夾複製C:\Users\dongj\Desktop\百度\ueditor-1.4.3.3\jsp\src 下,把com文件夾複製到項目的java代碼中:結構如下圖所示。
接下來我將介紹我修改的步驟(以修改上傳圖片路徑爲例):
首先在ConfigManager類中增加一屬性用來存放上傳路徑:
package com.baidu.ueditor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.baidu.ueditor.define.ActionMap;
/**
* 配置管理器
* @author [email protected]
*
*/
public final class ConfigManager {
private final String phyPath;
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 phyPath, String rootPath, String contextPath, String uri ) throws FileNotFoundException, IOException {
rootPath = rootPath.replace( "\\", "/" );
phyPath = phyPath.replace( "\\", "/" );
this.phyPath = phyPath;
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 phyPath, String rootPath, String contextPath, String uri ) {
try {
return new ConfigManager(phyPath,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 );
conf.put( "phyPath", this.phyPath );
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;
}
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]*?\\*/", "" );
}
}
相應的ActionEnter類做如下調整:
package com.baidu.ueditor;
import com.baidu.ueditor.define.ActionMap;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.hunter.FileManager;
import com.baidu.ueditor.hunter.ImageHunter;
import com.baidu.ueditor.upload.Uploader;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class ActionEnter {
private HttpServletRequest request = null;
private String phyPath = null;
private String rootPath = null;
private String contextPath = null;
private String actionType = null;
private ConfigManager configManager = null;
public ActionEnter ( HttpServletRequest request, String rootPath , String phyPath ) {
this.request = request;
this.phyPath = phyPath;
this.rootPath = rootPath;
this.actionType = request.getParameter( "action" );
this.contextPath = request.getContextPath();
this.configManager = ConfigManager.getInstance( this.phyPath, this.rootPath, this.contextPath, request.getRequestURI() );
}
public String exec () {
String callbackName = this.request.getParameter("callback");
if ( callbackName != null ) {
if ( !validCallbackName( callbackName ) ) {
return new BaseState( false, AppInfo.ILLEGAL ).toJSONString();
}
return callbackName+"("+this.invoke()+");";
} else {
return this.invoke();
}
}
public String invoke() {
if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
}
if ( this.configManager == null || !this.configManager.valid() ) {
return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
}
State state = null;
int actionCode = ActionMap.getType( this.actionType );
Map<String, Object> conf = null;
switch ( actionCode ) {
case ActionMap.CONFIG:
return this.configManager.getAllConfig().toString();
case ActionMap.UPLOAD_IMAGE:
case ActionMap.UPLOAD_SCRAWL:
case ActionMap.UPLOAD_VIDEO:
case ActionMap.UPLOAD_FILE:
conf = this.configManager.getConfig( actionCode );
state = new Uploader( request, conf ).doExec();
break;
case ActionMap.CATCH_IMAGE:
conf = configManager.getConfig( actionCode );
String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
state = new ImageHunter( conf ).capture( list );
break;
case ActionMap.LIST_IMAGE:
case ActionMap.LIST_FILE:
conf = configManager.getConfig( actionCode );
int start = this.getStartIndex();
state = new FileManager( conf ).listFile( start );
break;
}
return state.toJSONString();
}
public int getStartIndex () {
String start = this.request.getParameter( "start" );
try {
return Integer.parseInt( start );
} catch ( Exception e ) {
return 0;
}
}
/**
* callback參數驗證
*/
public boolean validCallbackName ( String name ) {
if ( name.matches( "^[a-zA-Z_]+[\\w0-9_]*$" ) ) {
return true;
}
return false;
}
}
修改BinaryUploader類中的方法:
至此,後端配置已完成。
接下來修改controller.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
import="com.baidu.ueditor.ActionEnter"
pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%
request.setCharacterEncoding( "utf-8" );
response.setHeader("Content-Type" , "text/html");
String physicalPath = "D:\\A";
String rootPath = application.getRealPath( "/" );
out.write( new ActionEnter( request, rootPath,physicalPath ).exec() );
%>
其中physicalPath爲上傳資源路徑。
修改config.json如下:
其中imageUrlPrefix爲tomcat虛擬路徑訪問地址。
注:如果不設置虛擬路徑,並配上地址本項目將無法顯示圖片(可在tomcat上配),具體設置方法請自行百度。
至此,項目配置完成。可運行!
由於個人能力有限,文筆不太好。如有問題請不吝賜教。